Skip to content

Commit ef30621

Browse files
NikhilJoshi28t2013anurag
authored andcommitted
Insertion Sort in CPP (#995)
1 parent f75fc3e commit ef30621

File tree

1 file changed

+46
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)