# Sorting 2D arrays

Page 1 of 1

## 2 Replies - 3520 Views - Last Post: 05 December 2012 - 03:55 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=302791&amp;s=3c72b106ee4547b3c8d99e98e1381f30&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 whwhwh

Reputation: 0
• Posts: 1
• Joined: 04-December 12

# Sorting 2D arrays

Posted 04 December 2012 - 09:13 PM

So I'm in the middle of a program... part of it requires me to write a function to take a 2D array (maximum 20x20) from a file and sort each row. For example:
9 4 2 1 would become 1 2 4 9
3 5 6 2 ------------ 2 3 5 6

Also, I need to write another function to sort the columns of a 2D array in descending order.
1 2 3 would become 7 8 9
4 5 6 ------------ 4 5 6
7 8 9 ------------ 1 2 3

I am having trouble forming the logic to complete these functions. Any help would be much appreciated.

Is This A Good Question/Topic? 0

## Replies To: Sorting 2D arrays

### #2 azemyth

Reputation: 2
• Posts: 26
• Joined: 12-December 11

## Re: Sorting 2D arrays

Posted 05 December 2012 - 01:25 AM

not a problem at all
the easiest sorting algorithm i know is "selected sort". search for it in the web and apply it for each row in given matrix.
for the second, even easier, just replace first value of matrix with the last (use temporary variable). you need know know well how to play with indexes.

• D.I.C Lover

Reputation: 331
• Posts: 1,168
• Joined: 01-April 11

## Re: Sorting 2D arrays

Posted 05 December 2012 - 03:55 PM

The hard part about sorting a 2D array is that you will need to add an extra for loop.

So a 1D array will have two nested for loops:

```for(i=0;i<SIZE;i++) {
for(j=0;j<SIZE-1;j++) {
if(array[j] < array[j+1])
//make the swap
}
}

```

Notice how the j loop goes over all the array values, and the i loop makes sure that the j loop is executed once for every element in the array.

When you move to a 2D array, you need to add one more nested for loop. Say you're using Selection sort:

```for(c=0;c<SIZE;c++) {   //as expected, the columns go to the outer for loop
for(i=0;i<SIZE;i++)  //this is unexpected - just ensures that the inner loop is run SIZE times for each column
//you can't use the column variable c, as the iterator for this loop.
min = i;
for(r=i+1;r<SIZE;r++) //as expected, the rows have to be in the inner loop, for a column sort.
if(a[r][c] < a[min][c])
min=r;
//etc.

```

It's adding the for(i) loop that is the stumbling block for most.