2

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

1
  • select all the code then press ctrl+k , and what sorting algorithm are you using ? Commented Oct 16, 2013 at 19:09

1 Answer 1

1

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.