-
Notifications
You must be signed in to change notification settings - Fork 3
/
insersionSort.cpp
73 lines (60 loc) · 1.76 KB
/
insersionSort.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
INSERTION SORT!
The array is virtually split into a sorted and an unsorted part.
Values from the unsorted part are picked and placed at the correct position in the sorted part.
1st element is considered first and kept in the sorted part, second element is compared with it and is kept accordingly in the sorted part.
This continues till all elements are placed correctly.
Time complexities:
worst case: O(n²) //array is in desending order
average case: O(n²)
best case: O(n) //already sorted array
*/
#include <iostream>
using namespace std;
int main(){
int n;
cout<<"Enter the number of elements in the array: ";
cin>>n;
int arr[n];
//making an array
for(int i=0;i<n;i++){
cout<<"Enter the "<<i<<" element of the array: ";
cin>>arr[i];
}
cout<<"The given array is: ";
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
//insertion-sorting
for(int i=1;i<n;i++){
int current = arr[i];
int j=i-1;
while(j>=0 && arr[j]>current){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=current;
}
//printing insertion-sorted array.
cout<<"\nThe Insertion Sorted array is: ";
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}
/*
Illustration:
array -> {12, 4, 1, 10}
^ ^
{4, 12, 1, 10}
^ ^
{4, 1, 12, 10}
^ ^
{1, 4, 12, 10}
^ ^
{1, 4, 10, 12} //completely sorted array
// no need of further comparisons
*/
/*
code written by Aditya Bijapurkar
*/