Skip to content

Commit 291fdb4

Browse files
Create insertion_sort.cpp
1 parent 46937dc commit 291fdb4

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
#include <iostream>
3+
using namespace std;
4+
void display(int *array, int size)
5+
{
6+
for (int i = 0; i < size; i++)
7+
cout << array[i] << " ";
8+
cout << endl;
9+
}
10+
void insertionSort(int *array, int size)
11+
{
12+
int key, j;
13+
for (int i = 1; i < size; i++)
14+
{
15+
key = array[i]; //take value
16+
j = i;
17+
while (j > 0 && array[j - 1] > key)
18+
{
19+
array[j] = array[j - 1];
20+
j--;
21+
}
22+
array[j] = key;
23+
}
24+
}
25+
int main()
26+
{
27+
int n;
28+
cout << "Enter the number of elements: ";
29+
cin >> n;
30+
int arr[n]; //create an array with given number of elements
31+
cout << "Enter elements:" << endl;
32+
for (int i = 0; i < n; i++)
33+
{
34+
cin >> arr[i];
35+
}
36+
cout << "Array before Sorting: ";
37+
display(arr, n);
38+
insertionSort(arr, n);
39+
cout << "Array after Sorting: ";
40+
display(arr, n);
41+
}

0 commit comments

Comments
 (0)