Skip to content

Commit 7074c0c

Browse files
committed
Added Insertion sort in c++
1 parent 570f0cc commit 7074c0c

File tree

2 files changed

+47
-37
lines changed

2 files changed

+47
-37
lines changed

Sorting/Insertion_Sort.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#include <iostream>
2+
#include <math.h>
3+
using namespace std;
4+
5+
/* Function to sort an array using insertion sort*/
6+
void insertionSort(int arr[], int n)
7+
{
8+
int i, key, j;
9+
for (i = 1; i < n; i++)
10+
{
11+
key = arr[i];
12+
j = i-1;
13+
14+
/* Move elements of arr[0..i-1], that are
15+
greater than key, to one position ahead
16+
of their current position */
17+
while (j >= 0 && arr[j] > key)
18+
{
19+
arr[j+1] = arr[j];
20+
j = j-1;
21+
}
22+
arr[j+1] = key;
23+
}
24+
}
25+
26+
// A utility function ot print an array of size n
27+
void printArray(int arr[], int n)
28+
{
29+
int i;
30+
for (i=0; i < n; i++)
31+
cout<<arr[i]<<endl;
32+
33+
}
34+
35+
36+
37+
/* Driver program to test insertion sort */
38+
int main()
39+
{
40+
int arr[] = {12, 11, 13, 5, 6};
41+
int n = sizeof(arr)/sizeof(arr[0]);
42+
43+
insertionSort(arr, n);
44+
printArray(arr, n);
45+
46+
return 0;
47+
}

Sorting/Insertion_sort.cpp

Lines changed: 0 additions & 37 deletions
This file was deleted.

0 commit comments

Comments
 (0)