Skip to content

Commit 5e5a92d

Browse files
Insertion sort
1 parent ea338f8 commit 5e5a92d

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

SortingAlgorithms/insertionsort.cpp

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*Enter number of elements: 5
2+
3+
Enter 5 elements
4+
4 3 5 1 2
5+
6+
Original List
7+
4 3 5 1 2
8+
Sorted List in Ascending Order
9+
1 2 3 4 5
10+
Sorted List in Descending Order
11+
5 4 3 2 1 */
12+
13+
#include<iostream>
14+
using namespace std;
15+
int main ()
16+
{
17+
int n;
18+
cout << "Enter number of elements: ";
19+
cin >> n;
20+
int *arr = new int [n];
21+
cout<<"\nEnter "<< n <<" elements\n";
22+
// add elemnts
23+
for(int i = 0; i < n; i++)
24+
cin >> arr[i];
25+
//print original array
26+
cout<<"\nOriginal List\n";
27+
for(int i=0;i<n;i++)
28+
cout <<arr[i]<<" ";
29+
for(int i=1; i<n; i++)
30+
{
31+
int temp = arr[i]; //store the key
32+
int j= i-1;
33+
// search a lower for insertion
34+
while(j>=0 && temp <= arr[j])
35+
{
36+
arr[j+1] = arr[j];
37+
j = j-1;
38+
}
39+
arr[j+1] = temp;
40+
}
41+
cout<<"\nSorted List in Ascending Order\n";
42+
// print the new list
43+
for(int i=0;i<n;i++)
44+
cout <<arr[i]<<" ";
45+
for(int i=1; i<n; i++)
46+
{
47+
int temp = arr[i];
48+
int j= i-1;
49+
//do similarly as above only now search for greater number
50+
while(j>=0 && temp >= arr[j])
51+
{
52+
arr[j+1] = arr[j];
53+
j = j-1;
54+
}
55+
arr[j+1] = temp;
56+
}
57+
// print the new list
58+
cout<<"\nSorted List in Descending Order\n";
59+
for(int i=0;i<n;i++)
60+
cout <<arr[i]<<" ";
61+
}

0 commit comments

Comments
 (0)