Skip to content

Commit e19e8e6

Browse files
authored
Merge pull request #742 from nlok5923/insertioncode
Added insertion_sort [C++]
2 parents d4b5b4e + 2c4209b commit e19e8e6

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

insertion_sort/insertion_sort.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
void insertionSort(int array[], int size)
4+
{
5+
int i = 0, tempElement = 0, j = 0;
6+
for (i = 1; i < size; i++)
7+
{
8+
tempElement = array[i]; //Choosing element whose correct index to be found.
9+
j = i - 1;
10+
while (j >= 0 && array[j] > tempElement)
11+
{
12+
array[j + 1] = array[j]; //Shifting element one position right side untill we get correct position
13+
j = j - 1;
14+
}
15+
array[j + 1] = tempElement; // got the correct position for tempElement
16+
}
17+
}
18+
void display(int array[], int size)
19+
{
20+
int i = 0;
21+
for (i = 0; i < size; i++)
22+
cout << array[i] << " ";
23+
cout << endl;
24+
}
25+
int main()
26+
{
27+
int size;
28+
cout<<"Enter the size of the array :"<<endl;
29+
cin>>size; //size of the array
30+
int array[size];
31+
cout<<"Enter array elements"<<endl;
32+
for(int i=0;i<size;i++)
33+
cin>>array[i]; //taking input
34+
cout << "unsorted array is :" << endl;
35+
display(array, size); //display unsorted array
36+
insertionSort(array, size);
37+
cout << "sorted array is :" << endl;
38+
display(array, size); //display the sorted array
39+
}

0 commit comments

Comments
 (0)