2013-10-16 36 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; 
    }