sorting arrays

I was serching for an easyer way to sort array elements form lagest to the smallest.
i used to use this, but with many numbers it's just rubbish to rewright everything.

1
2
3
4
5
6
7
for (int i = 0; i< n - 1; i++ ) 
  for (int j = i + 1; j < n; j++) 
    if (a[j] > a[i]) 
     { int sk = a[i]; 
       a[i] = a[j];
       a[j]=sk; 
     }

So lets say i have this:

3
Name 2010 12 25 1500
NAme 2011 01 15 1111
NAMe 2010 11 01 1211

and i would need to sort the list according to the last number (1500,1211,1111) so that it would look like this:
Name 2010 12 25 1500
NAMe 2010 11 01 1211
NAme 2011 01 15 1111


each number has its own array (e.g. 2010,2011,2010 is in one array and so on)
SO i guess what im asking for is a more simple way to sort stuff with many elements at the same time.
Last edited on
easyer way to sort array elements
1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
#include <algorithm>

int main()
{
    const int size = 6;
    int array[size ] = {1, 4, 6, 3, 2, 5};
    std::sort(array, array + size);
    for(int i: array) 
        std::cout << i << ' ';
}
1 2 3 4 5 6 
http://coliru.stacked-crooked.com/a/0e08f8d7e166ea6b

sort stuff with many elements at the same time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <algorithm>
#include <string>

struct stuff
{
    std::string name;
    int year;
    int x;
    int y;
    int z;
};

//Comparator
bool compare_years(const stuff& lhs, const stuff& rhs)
{
    return lhs.year < rhs.year;
}

void print_stuff(const stuff& s)
{
    std::cout << s.name << ' ' << s.year << ' ' << s.x << ' ' << s.y << ' ' << s.z << '\n';
}

int main()
{
    const int size = 3;
    stuff array[size] = {{"Name", 2010, 12, 25, 1500}, {"NAme", 2011, 01, 15, 1111}, {"NAMe", 2010, 11, 01, 1200}};
    std::sort(array, array + size, compare_years);
    for(const auto& s: array) 
        print_stuff(s);
    std::cout << '\n';
    std::sort(array, array + size, [](auto& lhs, auto& rhs){ return lhs.z < rhs.z; });
    for(const auto& s: array) 
        print_stuff(s);
}
Name 2010 12 25 1500
NAMe 2010 11 1 1200
NAme 2011 1 15 1111

NAme 2011 1 15 1111
NAMe 2010 11 1 1200
Name 2010 12 25 1500
http://coliru.stacked-crooked.com/a/f4e2b25613a39453
damn that's complicated :D
This is actually pretty easy.
Actual sorting is dony by simply calling
1
2
3
4
std::sort(beginning_of_range, end_of_range);
//or
std::sort(beginning_of_range, end_of_range, function_to_compare);
//Default comparison function is operator < 

You will need to define your own comparison function for your own classes, but it usually easy: lines 15-18 defines one, and different one defined inside sort call itself on line 33

The struct here to gather all related stuff in one object (having parallel arrays is almost never a good choice)

Topic archived. No new replies allowed.