You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: lessons/insertion.md
+126Lines changed: 126 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -5,3 +5,129 @@ order: "5E"
5
5
section: "Searching & Sorting"
6
6
description: "learn Sorting algorithms"
7
7
---
8
+
Insertion sort is the sorting mechanism where the sorted array is built having one item at a time. The array elements are compared with each other sequentially and then arranged simultaneously in some particular order.
9
+
10
+
## Explanation
11
+
12
+
The first element of the array forms the sorted subarray while the rest create the unsorted subarray from which we choose an element one by one and **insert** the same in the sorted subarray. The same procedure is followed until we reach the end of the array.
13
+
14
+
In each iteration, we extend the sorted subarray while shrinking the unsorted subarray. The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array).
15
+
16
+
* If it is the first element, it is already sorted. return 1;
17
+
* Pick next element
18
+
* Compare with all elements in the sorted sub-list
19
+
* Shift all the elements in the sorted sub-list that is greater than the value to be sorted
20
+
* Insert the value
21
+
* Repeat until list is sorted
22
+
23
+
## Pseudocode
24
+
```pseudocode
25
+
procedure insertionSort( A : array of items )
26
+
int holePosition
27
+
int valueToInsert
28
+
29
+
for i = 1 to length(A) inclusive do:
30
+
31
+
/* select value to be inserted */
32
+
valueToInsert = A[i]
33
+
holePosition = i
34
+
35
+
/*locate hole position for the element to be inserted */
36
+
37
+
while holePosition > 0 and A[holePosition-1] > valueToInsert do:
38
+
A[holePosition] = A[holePosition-1]
39
+
holePosition = holePosition -1
40
+
end while
41
+
42
+
/* insert the number at hole position */
43
+
A[holePosition] = valueToInsert
44
+
45
+
end for
46
+
47
+
end procedure
48
+
```
49
+
50
+
51
+
52
+
## Complexity analysis
53
+
54
+
Insertion sort runs in *O*(*n*) time in its best case and runs in *O*(*n*²) in its worst and average cases.
55
+
56
+
### Best case
57
+
58
+
Insertion sort performs two operations: it scans through the list, comparing each pair of elements, and it swaps elements if they are out of order. Each operation contributes to the running time of the algorithm. If the input array is already in sorted order, insertion sort compares *O*(*n*) elements and performs no swaps. Therefore, in the best case, insertion sort runs in O(*n*) time.
59
+
60
+
### Worst case
61
+
62
+
The worst case for insertion sort will occur when the input list is in decreasing order. To insert the last element, we need at most *n*−1 comparisons and at most *n*−1 swaps. To insert the second to last element, we need at most *n*−2 comparisons and at most *n*−2 swaps, and so on. The number of operations needed to perform insertion sort is therefore: 2 × (1+2+⋯+*n* −2+*n* −1) . This is in the order of sum of first n-1 numbers which is quadratic in nature. therefore, in the worst case, insertion sort runs in O(*n*²) time.
63
+
64
+
65
+
66
+
> The average case and the worst case have the same time complexity. Try to think why is this happening.
67
+
68
+
69
+
70
+
## Code Implementation
71
+
72
+
```java
73
+
74
+
// Java program for implementation of Insertion Sort
75
+
publicclassInsertionSort {
76
+
publicstaticvoidinsertionSort(int[] input) {
77
+
for (int i =1; i < input.length; i++) {
78
+
int j = i -1;
79
+
int temp = input[i];
80
+
for (; j >=0&& input[j] > temp; j--) {
81
+
input[j +1] = input[j];
82
+
}
83
+
input[j +1] = temp;
84
+
}
85
+
}
86
+
87
+
publicstaticvoidmain(String[] args) {
88
+
int[] input = { 1, 5, 4, 2, 3 };
89
+
insertionSort(input);
90
+
for (int j : input) {
91
+
System.out.print(j +"");
92
+
}
93
+
}
94
+
}
95
+
```
96
+
97
+
>
98
+
>
99
+
>Explanation of the example arr [] = {1 , 5 , 4 , 2 , 3 }
100
+
>
101
+
>Step 1 : No element on the left side of 1. so, no change in position.
102
+
>
103
+
>Step 2 : As 1 < 5. so no change in position.
104
+
>
105
+
>Step 3 : As 5 > 4. 4 and 5 will swap. now 1 < 4. so no change in postion.
106
+
>
107
+
>Step 4 : As 5 > 2. 2 and 5 will swap. now 4 > 2 so 2 and 4 will swap. now 1 < 2, so no change in position.
108
+
>
109
+
>Step 5: As 5 > 3. 3 and 5 will swap. now 4 > 3 so 3 and 4 will swap. now 2 < 3, so no change in position.
110
+
111
+
Now our array is sorted.
112
+
113
+
you can visualize this at [hackerearth](https://www.hackerearth.com/practice/algorithms/sorting/insertion-sort/visualize/)
114
+
115
+
## Advantages
116
+
117
+
- Simple and easy to understand implementation
118
+
- Efficient for small data
119
+
- If the input list is sorted beforehand (partially) then insertions sort takes `**O(n+d)**` where d is the number of inversions
120
+
- Chosen over bubble sort and selection sort, although all have worst case time complexity as `**O(n^2)**`
121
+
- Maintains relative order of the input data in case of two equal values (stable)
122
+
- It requires only a constant amount `**O(1)**` of additional memory space (in-place Algorithm)
123
+
124
+
125
+
126
+
## Applications
127
+
128
+
- It could be used in sorting small lists.
129
+
- It could be used in sorting "almost sorted" lists.
130
+
- It could be used to sort smaller sub problem in Quick Sort.
0 commit comments