Skip to content

Commit 23176c6

Browse files
Create insertionSort.cpp
1 parent 1490f07 commit 23176c6

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

insertionSort.cpp

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Insertion sort in C++
2+
3+
#include <iostream>
4+
using namespace std;
5+
6+
// Function to print an array
7+
void printArray(int array[], int size) {
8+
for (int i = 0; i < size; i++) {
9+
cout << array[i] << " ";
10+
}
11+
cout << endl;
12+
}
13+
14+
void insertionSort(int array[], int size) {
15+
for (int step = 1; step < size; step++) {
16+
int key = array[step];
17+
int j = step - 1;
18+
19+
// Compare key with each element on the left of it until an element smaller than
20+
// it is found.
21+
// For descending order, change key<array[j] to key>array[j].
22+
while (key < array[j] && j >= 0) {
23+
array[j + 1] = array[j];
24+
--j;
25+
}
26+
array[j + 1] = key;
27+
}
28+
}
29+
30+
// Driver code
31+
int main() {
32+
int data[] = {9, 5, 1, 4, 3};
33+
int size = sizeof(data) / sizeof(data[0]);
34+
insertionSort(data, size);
35+
cout << "Sorted array in ascending order:\n";
36+
printArray(data, size);
37+
}
38+
39+
//This code is contributed by prasant Kumar

0 commit comments

Comments
 (0)