2013-10-16 37 views
2

在索引和存儲我有一排具有相同數字的二維數組。
我必須按升序查找元素的索引並將其放入另一個數組中。
例如,假設輸入陣列具有的以下數字:排序二維數組,並找到一個陣列

int test[5][2]= { {12,12},{3,3},{14,14},{5,5},{8,8} }. 

我必須輸出在結果陣列:

result[5] = {1,3,4,0,2}. 

只是以遞增順序的元素的索引...
我寫了這個程序,但結果陣列始終是1

int main() 
{ 
    int N=5; 
    int result[5]; 
    int test[5][2] = { {12,12},{3,3},{14,14},{5,5},{8,8} }; 
    int i,j; 
    int smallindex = 0; 

    for (j=0; j<5; j++) 
    { 
     for (i=1; i<5; i++) 
     { 
      if (test[i][0] < test[i-1][0]) 
      { 
       smallindex=i; 
      } 
     } 
     result[j]=smallindex; 
    } 

    for (j=0; j<5; j++) 
    { 
     printf("%d \t ", result[j]); 
    } 
} 

人告訴我這是什麼問題?

感謝

+0

選擇所有的代碼,然後按ctrl + k,你使用什麼排序算法? –

回答

1

做少量修改代碼中的if聲明。

for(i=0;i<5;i++) 
    { 
    smallindex=0; 
    for(j=0;j<5;j++) { 
     //try to avoid comparing same element by checking i==j 
     if(test[i][0]<test[j][0]) 
      smallindex++; // check each element with all elements.count how many elements are greater than specific element.increment count and at the end of inner loop assign to result array. 
     } 

    result[i]=smallindex; 
    }