-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsorting.cpp
More file actions
61 lines (49 loc) · 1.35 KB
/
sorting.cpp
File metadata and controls
61 lines (49 loc) · 1.35 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Sorting in C++
*
* We rarely implement Bubble/Merge/Quick sort from scratch in CP.
* We use std::sort which is highly optimized (IntroSort: Hybrid of Quick, Heap, and Insertion Sort).
* Complexity: O(N log N).
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Custom Comparator
// Sorts in descending order
bool compareDesc(int a, int b) {
return a > b;
}
struct Person {
string name;
int age;
int score;
};
// Sort by score descending, then by age ascending
bool comparePerson(const Person& a, const Person& b) {
if(a.score != b.score) return a.score > b.score;
return a.age < b.age;
}
int main() {
vector<int> v = {4, 2, 5, 1, 3};
// 1. Basic Sort (Ascending)
sort(v.begin(), v.end());
cout << "Sorted: ";
for(int x : v) cout << x << " ";
cout << "\n";
// 2. Sort Descending using simple Comparator
sort(v.begin(), v.end(), compareDesc);
// Alternatively: sort(v.begin(), v.end(), greater<int>());
// 3. Struct Sorting
vector<Person> people = {
{"Alice", 25, 100},
{"Bob", 20, 90},
{"Charlie", 22, 100}
};
sort(people.begin(), people.end(), comparePerson);
cout << "People Sorted:\n";
for(auto& p : people) {
cout << p.name << " (Age: " << p.age << ", Score: " << p.score << ")\n";
}
return 0;
}