]> Skullheadx's Git Forge - Sorting.git/commitdiff
create insertion sort
authorSkullheadx <704277@pdsb.net>
Tue, 24 Jan 2023 23:18:44 +0000 (18:18 -0500)
committerSkullheadx <704277@pdsb.net>
Tue, 24 Jan 2023 23:18:44 +0000 (18:18 -0500)
sorting_algorithms/insertion_sort.py

index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..faa4ad44d337e42b1311b6bab53598f1f6dd92cc 100644 (file)
@@ -0,0 +1,11 @@
+# Insertion Sort (O(n^2))
+
+def insertion_sort(array):
+    for index1 in range(1, len(array)):  # look at second element
+        for index2 in range(0, index1):  # loop through each of previous elements to find where to insert
+            if array[index2] > array[index1]:  # find where in the sorted portion to put next element
+                array.insert(index2, array[index1])  # insert smaller element into sorted portion
+                del array[index1 + 1]  # +1 because inserted an element
+                break  # already inserted element, move on to the next element
+    return array  # return sorted array
+