5

I am trying to sort a 2 dimensional array.the original array is

5 0 3
4 1 2
3 1 1
4 2 2
3 3 1

When sorted, it should be like

3 1 1
3 3 1
4 2 2
4 1 2
5 0 3

Here is the code i used trying to implement Bubble Sort,i represents the number of rows.

int x,y,z,j,temp1,temp2,temp3;
for(x=0;x<i;x++)
{
    for (j=0;j<i-1;j++)
    {
        if(a[j][0]>a[j+1][0])
        {
            temp1=a[j][0];
            temp2=a[j][1];
            temp3=a[j][2];
            a[j][0]=a[j+1][0];
            a[j][1]=a[j+1][1];
            a[j][2]=a[j+1][2];
            a[j+1][0]=temp1;
            a[j+1][1]=temp2;
            a[j+1][2]=temp3;
        }
    }
}

it still does not sort, any help will be greatly appreciated.

7
  • 13
    Your bracket style is curious. Commented Dec 30, 2012 at 17:05
  • 9
    Why does 4 2 2 come before 4 1 2? Commented Dec 30, 2012 at 17:06
  • 1
    A good hint is you don't use the variable x outside of its loop. Commented Dec 30, 2012 at 17:07
  • Are you trying to sort rows or columns? Commented Dec 30, 2012 at 17:09
  • 2
    If you are sorting according to first column, then you are simply sorting a 1d array. Lots of algos for that .. Commented Dec 30, 2012 at 17:26

1 Answer 1

3

It looks like you are trying to sort the rows of the array in lexicographical order. If you treat the 2D array as an array of arrays, then you are just sorting the second-level arrays within the first-level array into ascending lexicographical order.

Depending on whether the number of columns in your array is fixed, you might be able to do this using the qsort function with a custom comparator. For example, if you know that there will always be exactly 3 elements in each column, you could write a comparator like this one:

static const size_t NUM_COLS = 3;

/* Lexicographically compare two arrays of size NUM_COLS. */
int CompareArrays(const void* arr1, const void* arr2) {
     /* Convert back to the proper type. */
     const int* one = (const int*) arr1;
     const int* two = (const int*) arr2;

     /* Do an element-by-element comparison.  If a mismatch is found, report how
      * the arrays compare against one another.
      */
     for (size_t i = 0; i < NUM_COLS; i++) {
         if (one[i] < two[i]) return -1;
         if (one[i] > two[i]) return +1;
     }

     /* If we get here, the arrays are equal to one another. */
     return 0;
}

/* Use qsort to sort the arrays */
qsort((const int*)&one, numRows, sizeof(int[NUM_COLS]), CompareArrays);

Hope this helps!

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.