-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinsertion.cpp
More file actions
48 lines (44 loc) · 798 Bytes
/
insertion.cpp
File metadata and controls
48 lines (44 loc) · 798 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
48
#include<iostream>
using namespace std;
void print_array(int *array,int size);
void insertion_sort(int *array,int size);
int main()
{
int size;
cout<<"Enter size of array : ";
cin>>size;
cout<<"Now enter element of array : ";
int *array = new int[size];
for(int i=0;i<size;i++)
{
cin>>array[i];
}
insertion_sort(array,size);
print_array(array,size);
}
void insertion_sort(int *array,int size)
{
int temp,j;
for(int i=1;i<size;i++)
{
j=i-1;
temp=array[i];
// search for correct position in array.
while(j>=0 && array[j]>temp)
{
array[j+1]=array[j];
j--;
}
// set correct position in array.
array[j+1]=temp;
}
}
void print_array(int *array,int size)
{
cout<<"Now element of array is : ";
for(int i=0;i<size;i++)
{
cout<<array[i]<<" ";
}
cout<<"\n";
}