-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathinsertion.cpp
83 lines (73 loc) · 1.6 KB
/
insertion.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
74
75
76
77
78
79
80
81
82
83
// EXECUTION OF INSERTION SORT IN C++
/*First we will compare first element in the list with its adjacent element.
And at every comparison if the element can be inserted at a particular position,
then it is inserted by shifting the other elements one position to the right.
The above steps are repeated until all the elements in the list are in their
appropriate position.i.e. list is in sorted order.*/
#include <iostream>
using namespace std;
// Function to print array.
void display(int arr[], int size) {
int i;
for (i=0; i < size; i++)
cout<< arr[i]<<"\t";
cout<<"\n";
}
// swapping elements in the array
void swap(int arr[], int i , int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Main function to run the program
int main()
{
int size;
cout << "Enter size of array:" << endl;
cin >> size;
int array[size];
cout << "Enter array elements:" << endl;
for (int i = 0; i < size; i++) {
cin >> array[i];
}
int i, j, k;
for (i = 1; i < size; i++)
{
// target = array[i];
// j = i - 1;
j = i-1;
k = i;
/* Here the elements in b/w arrary[0 to i-1]
which are greater than target are moved
ahead by 1 position each*/
while (j >= 0 && array[k] < array[j])
{
swap(array, k, j);
j--;
k--;
}
}
cout<<"After Insertion sort: \n";
display(array, size);
return 0;
}
/**
Enter the size of list:
6
Enter the numbers:
5
0
2
1
4
3
Sorted list:
0
1
2
3
4
5
Time Complexity: O(n*2)
Space Complexity: O(1)
*/