sundowatch
sundowatch

Reputation: 3103

C++ array value sorting

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.

Upvotes: 2

Views: 2581

Answers (5)

Xzhsh
Xzhsh

Reputation: 2239

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.

Upvotes: 1

Muhit
Muhit

Reputation: 787

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.

Upvotes: 1

bsruth
bsruth

Reputation: 5502

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);
}

Upvotes: 6

James McNellis
James McNellis

Reputation: 355307

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>());

Upvotes: 3

Scharron
Scharron

Reputation: 17817

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

Upvotes: 4

Related Questions