-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.cpp
More file actions
55 lines (45 loc) · 1.24 KB
/
Copy pathInsertionSort.cpp
File metadata and controls
55 lines (45 loc) · 1.24 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
#include <iostream>
using namespace std;
/* insertion sort algorithm */
void insertionSort(int array[], int size) {
for (int i = 1; i < size; i++) {
int currentElement = array[i];
int j = i - 1;
/* comparing each element from left of it
until smaller element is found */
/* for sorting in descending order, currentElement > array[j] */
while (j >= 0 && currentElement < array[j]) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = currentElement;
}
}
/* function to print array */
void display(int array[], int size) {
cout << "Array: ";
for (int i = 0; i < size; i++) {
cout << array[i] << " ";
}
cout << endl;
}
int main() {
// array of size 20
int array[20];
/* Enter the size of array */
int size;
cout << "Enter the size of array: ";
cin >> size;
/* array of size entered by user */
array[size];
/* enter array elements */
for (int i = 0; i < size; i++) {
cout << "Enter element at " << i << "th index: ";
cin >> array[i];
}
/* calling insertionSort function */
insertionSort(array, size);
/* printing array after sorting */
display(array, size);
return 0;
}