C++
x
44
1
2
3
4
5
void test(std::vector<int> array) { // intensionally passed by value6
std::cout << "before sorting:";7
for (int v : array) std::cout << ' ' << v;8
std::cout << '\n';9
10
std::sort(array.begin(), array.end(), [](int a, int b) -> bool {11
int pa, pb; // priority a/b12
13
if (a % 4 == 0) pa = 1;14
else if (a % 2 == 0) pa = 3;15
else pa = 2;16
17
if (b % 4 == 0) pb = 1;18
else if (b % 2 == 0) pb = 3;19
else pb = 2;20
21
// if the priority differs, sort according to the priority22
if (pa != pb) return pa < pb;23
// if both can be divided by 4, sort in descending order24
if (pa == 1) return b < a;25
// if both can be divided by 2 but not with 4, sort in ascending order26
if (pa == 3) return a < b;27
// no specific order for the rest28
return false;29
});30
31
std::cout << "after sorting:";32
for (int v : array) std::cout << ' ' << v;33
std::cout << '\n';34
}35
36
int main(void) {37
std::vector<int> array = {12, 10, 10, 9, 8, 8, 8};38
std::vector<int> array2 = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};39
test(array);40
std::cout << '\n';41
test(array2);42
return 0;43
}44
$ g++ prog.cc -Wall -Wextra -std=c++11 -pedantic
Start
before sorting: 12 10 10 9 8 8 8 after sorting: 12 8 8 8 9 10 10 before sorting: 10 9 8 7 6 5 4 3 2 1 after sorting: 8 4 9 7 5 3 1 2 6 10
0
Finish