views:

143

answers:

5

If I want to sort the second dimension's 0 element like that:

short arr[5];

arr[0][0] = 122;
arr[0][1] = 33;
arr[0][2] = 45;

arr[1][0] = 33;
arr[1][1] = 12;
arr[1][2] = 42;
.
.
.

It will sort arr[i][0], but arr[i][1] and arr[i][2] will come with arr[i][0] to a new element.

+4  A: 

This should help you : http://www.cplusplus.com/reference/algorithm/sort/

Scharron
+6  A: 

To sort a standard C array using the std::sort algorithm:

#include <algorithm>
    ...
    sort(&arr[0], &arr[0] + 5)

Now if you have a two dimensional array, you can use the same idea to sort the second dimension of each item in the first dimension:

short arr[5][5];
...
for(int i = 0; i < 5; ++i) {
   sort(&arr[i][0], &arr[i][0] + 5);
}
bsruth
+3  A: 

std::sort will, by default, sort objects in ascending order. To sort in descending order, you can use the std::greater function object:

std::sort(arr, arr + 5, std::greater<short>());
James McNellis
+2  A: 

There are too many sorting algorithms, like quicksort and bubble sort, with different complexity. And this complexity varies upon size of data set, default order of data within data set, etc. You have to study your data set and pick one algorithm that will meet your requirement faster. You can find sorting algorithms in http://en.wikipedia.org/wiki/Sorting_algorithm.

Muhit
Given that the standard library has `sort` (average case N log N) and `stable_sort` (worst case N (log N)^2), there is _very rarely_ a good reason to implement your own sorting algorithm.
James McNellis
+1  A: 

If this is a homework assignment, you probably don't want to use std::sort. Your teacher might consider you cheeky :P

I'd go with what Muhit said and try learning from Wikipedia's article on sorting algorithms, http://en.wikipedia.org/wiki/Sorting_algorithm. Most of the individual articles have the algorithms implemented in pseudocode, so you can just pick one to code up.

But if this is for a different project, yeah, definitely go with STL, there shouldn't really be any reason to code up a sorting algorithm by hand right now.

Xzhsh
It is not a homework assignment.
sundowatch