-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisort.cpp
60 lines (51 loc) · 1.09 KB
/
isort.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
#include <iostream>
void printArr(int arr[], int size) {
std::cout << "[ ";
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << "]" << std::endl;
}
class InsertionSort {
public:
InsertionSort(int *arr, int arr_size) : m_size(arr_size) {
m_arr = new int[arr_size];
std::copy(arr, arr+arr_size, m_arr);
};
~InsertionSort() {
delete m_arr;
};
void sort() {
for (int j = 1; j < m_size; j++) {
int key = m_arr[j];
int i = j - 1;
while (i >= 0 && m_arr[i] > key) {
m_arr[i + 1] = m_arr[i];
i--;
}
m_arr[i + 1] = key;
}
}
void sort_des() {
for (int j = 1; j < m_size; j++) {
int key = m_arr[j];
int i = j - 1;
while (i >= 0 && m_arr[i] < key) {
m_arr[i + 1] = m_arr[i];
i--;
}
m_arr[i + 1] = key;
}
}
public:
int m_size;
int *m_arr;
};
int main() {
int a[] = {2,4,3,1};
InsertionSort is = InsertionSort((int *)&a, std::size(a));
is.sort();
printArr(is.m_arr, is.m_size);
is.sort_des();
printArr(is.m_arr, is.m_size);
}