-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionSort.cpp
More file actions
53 lines (36 loc) · 1.26 KB
/
insertionSort.cpp
File metadata and controls
53 lines (36 loc) · 1.26 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
#include <iostream>
using namespace std;
// master feature
// master feature
bool prevElem_GTE_toInsert(int currentValue, int toInsertValue) {
return (currentValue >= toInsertValue);
}
void findInsertionPoint(int arr [], int outerIndex) {
int valueToInsert = arr[outerIndex];
int innerIndex = outerIndex;
cout << "\nFind niche to insert value " << valueToInsert << endl;
while (innerIndex > 0 &&
prevElem_GTE_toInsert(arr[innerIndex-1], valueToInsert)) {
arr[innerIndex] = arr[innerIndex-1];
innerIndex--;
}
cout << "\nniche found at: " << innerIndex << ", for value " << valueToInsert;
arr[innerIndex] = valueToInsert;
}
void insertionSort(int arr [], int size) {
cout << "\nSorting an array that is: " << size << endl;
for ( int outerIndex = 1; outerIndex <= size-1; outerIndex++) {
cout << "\n=== outerIndex: " << outerIndex << " ====" << endl;
findInsertionPoint(arr, outerIndex);
}
}
int main() {
int arr [] = {387, 3,1, 7,100, 2,88, 9,1};
int size = sizeof(arr) / sizeof(int);
insertionSort(arr, size);
cout << "\n---- result ----" << endl;
for ( int i = 0; i < size; i++) {
cout << arr[i] << endl;
}
return 0;
}