-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathInsertion_sort.cpp
More file actions
47 lines (37 loc) · 833 Bytes
/
Copy pathInsertion_sort.cpp
File metadata and controls
47 lines (37 loc) · 833 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
using namespace std;
int insertion_sort(int *arr , int n)
{
for(int i=1; i<n; i++)
{
int temp = arr[i] ;
int j = i - 1 ;
while(j>=0 && arr[j] > temp)
{
arr[j+1] = arr[j] ;
j -- ;
}
arr[j+1] = temp ;
}
return *arr ;
}
int main()
{
int arr[] = {8,4,1,5,9,2} ;
int n = sizeof(arr) / sizeof(arr[0]) ;
// print the unsorted array
cout << "unsorted array : " ;
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
// calling the function .
insertion_sort(arr, n) ;
cout << endl ;
// print the sorted array
cout << "sorted array : ";
for(int i=0; i<n; i++)
{
cout << arr[i] << " " ;
}
}