-
Notifications
You must be signed in to change notification settings - Fork 257
/
sort-integers.cpp
60 lines (57 loc) · 1.29 KB
/
sort-integers.cpp
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
// Time: O(n) ~ O(n^2)
// Space: O(1)
// In-place insertion sort. (stable)
class Solution {
public:
/**
* @param A an integer array
* @return void
*/
void sortIntegers(vector<int>& A) {
for (int n = 0; n < A.size(); ++n) {
for (int i = n - 1; i >= 0 && A[i] > A[i + 1]; --i) {
swap(A[i], A[i + 1]);
}
}
}
};
// Time: O(n^2)
// Space: O(1)
// Bubble sort. (stable)
class Solution {
public:
/**
* @param A an integer array
* @return void
*/
void sortIntegers(vector<int>& A) {
for (int n = 0; n < A.size(); ++n) {
for (int i = 0; i + 1 < static_cast<int>(A.size()) - n; ++i) {
if (A[i] > A[i + 1]) {
swap(A[i], A[i + 1]);
}
}
}
}
};
// Time: O(n^2)
// Space: O(1)
// Selection sort. (unstable)
class Solution {
public:
/**
* @param A an integer array
* @return void
*/
void sortIntegers(vector<int>& A) {
for (int n = 0; n < A.size(); ++n) {
int min_idx = n;
for (int i = n + 1; i < A.size(); ++i) {
if (A[i] < A[min_idx]) {
min_idx = i;
}
}
swap(A[n], A[min_idx]);
}
}
};