Skip to content

Commit aa0b082

Browse files
Update insertion_sort
1 parent d3d4cdc commit aa0b082

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

insertion_sort

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,24 @@
11
Insertion Sort Algorithm:
22
1. Assume the first element of the list is already sorted. Thus, the list is now divided into two sublists: sorted and unsorted.
3-
2. Compare the elements in unsorted list with those in sorted.
3+
2. Iterate over the unsorted elements.
4+
3. Save the unsorted elements in a variable so that it doesn't disappear with modified indices after comparison.
5+
4. Iterate over the sorted elements from len(sorted_elements) to 0, in backwards direction so that the unsorted one could be compared and we may find the correct index to insert it in the sorted list.
6+
5. With every iteration in the sorted list, we test if sorted element is greater than the unsorted element, if TRUE, swap the numbers or copy the greater sorted number to the index of smaller unsorted index. Remember, we have already stored current unsorted element being compared to a variable so we can not lose it with this copy.
7+
6. If we are swapping the sorted and unsorted elements, we should decrease the indices by 1 to keep comparing the same unsorted element with other sorted element(we are anyways moving backwards in sorted list/with sorted elements).
8+
7. When the condition in while loop fails, for loop continues which moves forward with another unsorted element and the process continues.
9+
10+
In Brief:
11+
1. Assume the first element of the list is already sorted. Thus, the list is now divided into two sublists: sorted and unsorted.
12+
2. Iterate over the unsorted elements.
413
3. If the element is less, swap the elements, decrease the indices of both the sorted and unsorted subset so that the correct position of unsorted element is found and it is then inserted.
514
4. Perform step 2 and 3 recursively or continuously until the indices representing sorted list reach 0.
615

16+
Insertion sort with swapping elements:
717

818
def insertion_sort(arr):
919
for i in range(1, len(arr)):
1020
"""val = arr[i]
21+
j = i
1122
while j>0 and arr[j-1]>val:
1223
arr[i], arr[j-1] = arr[j-1], arr[i]
1324
j -= 1
@@ -17,3 +28,16 @@ def insertion_sort(arr):
1728
arr[i], arr[j] = arr[j], arr[i]
1829
i -= 1
1930
# both loops are working fine, second one reduces number of lines.
31+
32+
If you have to copy the sorted elements and later place the unsorted element to its correct position:
33+
34+
for i in range(1, n):
35+
unsorted = arr[i]
36+
j = i-1
37+
while j>=0 and arr[j]>unsorted:
38+
arr[j+1]=arr[j]
39+
j-=1
40+
# print(' '.join(str(i) for i in arr))
41+
else:
42+
arr[j+1]=unsorted
43+
# print(' '.join(str(i) for i in arr))

0 commit comments

Comments
 (0)