forked from bumblebe-coding/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertionSort.cpp
44 lines (32 loc) · 1.42 KB
/
insertionSort.cpp
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
#include<bits/stdc++.h>
using namespace std;
//whenever we create a function using an array as an argument, we need to give the array size also. As when we pass the arguement, the function only knows the starting
//address of the array, not the size of the length of the array, so we need to specify the size in a second argument itself.
void insertionSort(int* arr, int size){
for(int i = 1; i < size; i++){//starts from the second element of the array
int num = arr[i]; //storing the value in a separate variable
int j = i - 1;//to compare all the values at lower indexes with value at index i
while(j >= 0 && arr[j] > num){//if the value is larger than the value at ith index
arr[j+1] = arr[j];
j--;
}
arr[j+1] = num;
}
}
int main(){
//the main driver code which takes the array as an input and prints the sorted array:
int n;
cout<<"enter the number of elements in the array: "<<endl;
cin>>n;
int arr[n];
cout<<"enter the elements: "<<endl;
for(int i = 0; i < n; i++)cin>>arr[i];
cout<<"size of the arr is: "<<sizeof(arr)/sizeof(int)<<endl;
cout<<"the unsorted array is: "<<endl;
for(int i = 0; i < 5; i++)cout<<arr[i]<<" ";
cout<<endl;
insertionSort(arr, n);
cout<<"the sorted array is: "<<endl;
for(int i = 0; i < n; i++)cout<<arr[i]<<" ";
cout<<endl;
}