Sorting multiple fields in one array

Hello,

I have a question about sorting data with 2 out of 3 fields in a array.

Example:

2 25 1000
4 10 1230
1 12 1540
2 5 1200
4 5 1250

Basically I want to cout this to:

1 12 1540
2 5 1200
2 25 1000
4 5 1250
4 10 1230

Can someone give me an example so that I can work it to my actual numbers? I searched around in the forum and internet but the only thing I can find is sorting one of the columns.

I need to sort the first column, then while keeping the order of the first column, descend the second column. Third column does not need to be in any order, but I just need to show it.

Also I cant use structures or classes. I can only use one array.

Thanks for your time,

Jason

Last edited on
The sort would probally be selection sort. But I only know how to sort one column. I would do it under a for loop with a x+1 as the test section, and then update my counter while couting what I am testing. But I just cant wrap my head around doing two. I am thinking it is a nested for loop within. But I cant think of trick to do it. My brain is spoiled by excel.
Ignore this: Read below.
Last edited on
If you want to do a selection sort you need to use a nested for loop which has O(n2) complexity.

1
2
3
4
5
6
7
8
9
10
11
for( int i = 0; i < height; i++)
{
    for( int j = 0; j < width; j++)
    {
          if(myArray[i][j] < myArray[0][0])
          {
               // This function swaps the cell in position i and j, with the first cell i.e. myArray[0][0]
               swapCells(i, j);
          }
    }
}
Last edited on
thank you!
Don't write a C program for this - if you are on an UNIX system, just use the command-line:

sort -k1,1n -k2,2n

stdin:
2 25 1000
4 10 1230
1 12 1540
2 5 1200
4 5 1250


stdout:
1 12 1540
2 5 1200
2 25 1000
4 5 1250
4 10 1230
Topic archived. No new replies allowed.