Tendo Games
Tendo Games

Reputation: 13

How to sort a 2d array from max to min

I have a 6 row and 2 column 2D array that needs to be sorted based on the values of the second column.

I understand that the bubble sort algorithm would work with a 1D array but I am confused how to compare specifically the second row.

for (int i = 1; i < 7; i++) {
    for (int j = i + 1; i < 7; i++) {
       int temp = copy[i][j];
       copy[i][j] = copy[j][i];
       copy[j][i] = temp;
    }
}

I expect my code to look like this:

1.0 10.0
2.0 8.0
3.0 11.0 
4.0 12.0 
5.0 2.0
6.0 7.0 

to this:

4.0 12.0
1.0 10.0
3.0 11.0
2.0 8.0
6.0 7.0 
5.0 2.0 

When using this code to sort the array I get just 1 value. As you can see above just the second column gets sorted.

Upvotes: 0

Views: 429

Answers (1)

gsamaras
gsamaras

Reputation: 73366

Why reinvent the wheel? Use qsort() from the C Standard Library, like this (generic example for any ROWSxCOLS matrix):

#include <stdio.h>      /* printf */
#include <stdlib.h>     /* qsort */
#define ROWS 6
#define COLS 2

int cmp(const void* p1, const void* p2)
{
  const float* arr1 = (const float*)p1;
  const float* arr2 = (const float*)p2;
  return (arr2[1] > arr1[1]) - (arr2[1] < arr1[1]);
}

int main(void)
{
  float array[ROWS][COLS] = {
    {1.0, 10.0},
    {2.0, 8.0},
    {3.0, 11.0},
    {4.0, 12.0},
    {5.0, 2.0},
    {6.0, 7.0}
  };

  qsort(array, ROWS, COLS * sizeof(float), cmp);

  for(int i = 0 ; i < ROWS; i++)
    printf("%f, %f\n", array[i][0], array[i][1]);

  return 0;
}

Output:

4.000000, 12.000000
3.000000, 11.000000
1.000000, 10.000000
2.000000, 8.000000
6.000000, 7.000000
5.000000, 2.000000

Upvotes: 1

Related Questions