Skip to content

Commit 65e6a11

Browse files
committed
Add Insertion Sort algorithm in C++
1 parent cfb6370 commit 65e6a11

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
* @author Abhishek Datta
3+
* @github_id abdatta
4+
* @since 15th October, 2017
5+
*
6+
* The following algroithm takes a list of numbers
7+
* and sorts them using the insertion sort algorithm.
8+
*/
9+
10+
#include <iostream>
11+
using namespace std;
12+
13+
// function to swap two numbers
14+
void swap(int *a, int *b)
15+
{
16+
int t = *a;
17+
*a = *b;
18+
*b = t;
19+
}
20+
21+
// function to perform insertion sort
22+
void insertion_sort(int *a, int n)
23+
{
24+
for (int i = 1; i < n; i++) // iterating over all the elements
25+
{
26+
int j = i; // j denotes the final position of the current element, which is initialised to the current position
27+
28+
while (j > 0 && a[j-1] > a[j]) // shift j until it is in the correct position
29+
{
30+
swap(a[j], a[j-1]); // swap with the shifted element
31+
j--;
32+
}
33+
}
34+
}
35+
36+
// main function to try the algorithm
37+
int main()
38+
{
39+
int n; // number of elements to be read
40+
41+
cin>>n;
42+
int *a = new int[n];
43+
44+
// reading a list of unsorted numbers
45+
for (int i = 0; i < n; ++i)
46+
cin>>a[i];
47+
48+
insertion_sort(a, n); // sorting the list
49+
50+
// printing the sorted list
51+
for (int i = 0; i < n; ++i)
52+
cout<<a[i]<<' ';
53+
cout<<endl;
54+
55+
return 0;
56+
}

0 commit comments

Comments
 (0)