user1667630
user1667630

Reputation: 297

sort a 2d array and find the index and store in a array

I have a 2d array which has same numbers in a row.
I have to find the index of the elements in increasing order and put it in another array.
For example, assume that the input array has the following numbers:

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

I have to output in result array with:

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

Just the index of the elements in increasing order...
I wrote this program, but the result array is always 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]);
    }
}

Can anyone tell me what is wrong in this?.

thanks

Upvotes: 2

Views: 452

Answers (1)

Gangadhar
Gangadhar

Reputation: 10516

Make little modification for if statement in your code.

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;
    }

Upvotes: 1

Related Questions