title: Sort complete matrix (2d array) by column
body: <p>Lets say I have a 2D array of n-by-m and I wand to sort it by a certain column, and have the rest of the columns "move" in the same order, as they have a "meaning" per row.</p>
  
  <p>example:</p>
  
  <pre><code> name   number  somethingrepeatable
  john    543       2
  peter   4312      4
  jane    234       2
  </code></pre>
  
  <p>Right now, the code that I have will sort the last column correctly, but will not distinguish between the john and jane row as the column the sort is applied on contains 2, giving me this as a result:</p>
  
  <pre><code>name    number  somethingrepeatable
  john    543        2
  jane    234        2
  peter   4312       4
  </code></pre>
  
  <p>More than asking for the code itself, I'm asking for an idea on how I could resolve this problem.</p>
  
  <p>This is my code so far:</p>
  
  <pre><code>- (Matrix*) sortByColumn: (NSUInteger) columnNumber{
  
  NSMutableArray * column_in_array = [[NSMutableArray alloc]init];
  
  for(int k=0;k&lt;[self numberOfRows];k++) @autoreleasepool{
      [column_in_array addObject: [self objectInRow:k column:columnNumber]];
  }
  
  
  
  NSSortDescriptor *sortDescriptor;
  sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:nil
                                                ascending:YES] autorelease];
  NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
  
  
  
  
  NSMutableArray *origPositions = [[NSMutableArray alloc]initWithCapacity:[orderedColumn count]];
  int pos;
  NSNumber *posNSI = [[NSNumber alloc]init];
  
  for(int i=0;i&lt;[orderedColumn count];i++){
      pos = (int)[column_in_array  indexOfObject:[orderedColumn objectAtIndex:i]];
      posNSI = [NSNumber numberWithInt:pos];
      [origPositions insertObject:posNSI atIndex:i];
  }
  
  
  
  
  Matrix * myReturnMatrix = [[Matrix alloc] initWithRows:[self numberOfRows]
                                        columns:[self numberOfColumns]];
  NSUInteger index;
  for(int i=0;i&lt;[self numberOfRows];i++){
      for(int j=0;j&lt;[self numberOfColumns];j++){
          index = [[origPositions objectAtIndex: i] integerValue];
          [myReturnArray setObject:[self objectInRow:index column:j] inRow:i column:j];
      }
  
  
  }
  
  return myReturnMatrix;
  </code></pre>
  
  <p>}</p>
  
  <p>A quick "explanation" would be: 
  I store the column I want to sort in an array, sort it using sortDescriptor, obtain the positions of the original column and sort the remaining columns using those original positions.</p>