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: insertion_sort
+25-1Lines changed: 25 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -1,13 +1,24 @@
1
1
Insertion Sort Algorithm:
2
2
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.
4
13
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.
5
14
4. Perform step 2 and 3 recursively or continuously until the indices representing sorted list reach 0.
6
15
16
+
Insertion sort with swapping elements:
7
17
8
18
def insertion_sort(arr):
9
19
for i in range(1, len(arr)):
10
20
"""val = arr[i]
21
+
j = i
11
22
while j>0 and arr[j-1]>val:
12
23
arr[i], arr[j-1] = arr[j-1], arr[i]
13
24
j -= 1
@@ -17,3 +28,16 @@ def insertion_sort(arr):
17
28
arr[i], arr[j] = arr[j], arr[i]
18
29
i -= 1
19
30
# 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:
0 commit comments