From: Skullheadx <704277@pdsb.net> Date: Tue, 24 Jan 2023 23:18:44 +0000 (-0500) Subject: create insertion sort X-Git-Url: http://git.skullheadx.com/sitemap.xml?a=commitdiff_plain;h=9178012afc358d14e15cc4166404ed8921402ca9;p=Sorting.git create insertion sort --- diff --git a/sorting_algorithms/insertion_sort.py b/sorting_algorithms/insertion_sort.py index e69de29..faa4ad4 100644 --- a/sorting_algorithms/insertion_sort.py +++ b/sorting_algorithms/insertion_sort.py @@ -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 +