-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathselection_sort.h
More file actions
49 lines (45 loc) · 1.05 KB
/
selection_sort.h
File metadata and controls
49 lines (45 loc) · 1.05 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
#ifndef SELECTION_SORT_HEADER
#define SELECTION_SORT_HEADER
#include "../helper/utils.h"
/**
* Section Sort
* Average complexity: O(n^2)
* Best Case: O(n^2)
* Worst Case: O(n^2)
* Space: O(1)
* Stable
*/
void selection_sort(int a[], int n) {
for (int i = 0; i < n - 1; ++i) {
int cur_min = i;
for (int j = i + 1; j < n; ++j)
if (a[cur_min] > a[j])
cur_min = j;
swap(a[cur_min], a[i]);
}
}
/**
* Section Sort Optimize
* Average complexity: O(n^2)
* Best Case: O(n^2)
* Worst Case: O(n^2)
* Space: O(1)
* Not Stable (Can make it Stable)
*/
void selection_sort_optimize1(int a[], int n) {
int r = n;
for (int i = 0; i < r - 1; ++i) {
int cur_min = i;
int cur_max = i;
for (int j = i + 1; j < r; ++j)
if (a[cur_min] > a[j])
cur_min = j;
else if (a[cur_max] < a[j])
cur_max = j;
swap(a[cur_min], a[i]);
if (cur_max == i) cur_max = cur_min;
--r;
swap(a[cur_max], a[r]);
}
}
#endif