2 Replies - 1268 Views - Last Post: 05 December 2012 - 03:55 PM Rate Topic: -----

#1 whwhwh  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 25
  • 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.
post your code anyway
Was This Post Helpful? 0
  • +
  • -

#3 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • 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.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1