forked from jYOTIHARODE/Hacktoberfest2021-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionSort.cpp
More file actions
49 lines (36 loc) · 828 Bytes
/
insertionSort.cpp
File metadata and controls
49 lines (36 loc) · 828 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
49
#include<iostream>
using namespace std;
void insertionSort(int a[],int size);
void printArray(int a[],int size);
int main(){
int n;
cout<<"Enter the size of the array: ";
cin>>n;
int arr[n];
cout<<"Enter the array to be sorted : \n";
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"\nInitial Array : \n";
printArray(arr,n);
insertionSort(arr,n);
cout<<"\nFinal Sorted (ascending) Array : \n";
printArray(arr,n);
return 0;
}
void insertionSort(int a[],int size){
int toInsert;
for(int i=1;i<size;i++){
toInsert=a[i];
int j;
for(j=i-1;j>=0 and a[j]>toInsert;j--){
a[j+1]=a[j];
}
a[j+1]=toInsert;
}
}
void printArray(int a[],int size){
for(int i=0;i<size;i++){
cout<<a[i]<<" ";
}
}