c++arrayssorting

Sorting an array according to other array


I have an array with arrays of two elements. Now I would like to sort all values ending at zero (e.g. arr[3][0], arr[1][0]) to be sorted from low to high.

Then I would like to have the values ending at 1 (e.g. arr[2][1], arr[1][1]) to also be sorted, but not on its own order, but in the same order as the first array.

Here is what I tried:

int compareInts(const void* a, const void* b)
{
    return ( *(int*) a[0] - *(int*) b[0] );
}

int arr[4][2];

arr[0][0] = 50;
arr[0][1] = 0;

arr[1][0] = 40;
arr[1][1] = 1;

arr[2][0] = 50;
arr[2][1] = 2;

arr[3][0] = 85;
arr[3][1] = 3;

qsort( arr, 4, sizeof(int), compareInts );


I would like to have the following result:

arr[0][0] = 40;
arr[0][1] = 1;

arr[1][0] = 50;
arr[1][1] = 0;

arr[2][0] = 50;
arr[2][1] = 2;

arr[3][0] = 85;
arr[3][1] = 3;

Solution

  • Just implement your own search algorithm (use bubble sort or whatever you think might be most efficient) and do the comparison/swapping similar to the following pseudo code:

    if(a[i][0] > a[j][0])
    {
        t[0] = a[i][0];
        t[1] = a[i][1];
        a[i][0] = a[j][0];
        a[i][1] = a[j][1];
        a[j][0] = t[0];
        a[j][1] = t[1];
    }
    

    If you'd like to sort based on multiple collumns you'd just have to repeat this comparing other sub array elements and sorting the least significant column first.

    Edit: I thik this should also be possible using qsort(). You just have to set the element size accordingly (should be 2 * sizeof(int) in your example). Leave the rest of your code unchanged (although I'm not sure about this and can't test run it right now).