sosytee
sosytee

Reputation: 1277

Sorting a 2 dimensional array in c

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.

Upvotes: 5

Views: 12761

Answers (1)

templatetypedef
templatetypedef

Reputation: 372714

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!

Upvotes: 3

Related Questions