Skip to content

Instantly share code, notes, and snippets.

@davidejones
Last active September 14, 2016 04:10
Show Gist options
  • Select an option

  • Save davidejones/e3b7b4f41263913c921b70e2f32fb57c to your computer and use it in GitHub Desktop.

Select an option

Save davidejones/e3b7b4f41263913c921b70e2f32fb57c to your computer and use it in GitHub Desktop.
attempt at an insertion sort
def inplace_insertion_sort(unsorted_list, split_index=None):
# if we have no split_index yet we know this is first iteration so lets split it
split_index = 1 if not split_index else split_index
# loop over each item in unsorted list
for uitem in unsorted_list[split_index:len(unsorted_list)]:
# reverse the sorted list to loop over as we compare right to left
for index, sitem in enumerate(reversed(unsorted_list[:split_index])):
if uitem > sitem:
# remove from unsorted so we don't look at it again
unsorted_list.remove(uitem)
# insert into list
unsorted_list.insert(len(unsorted_list[:split_index]) - index, uitem)
# move the split point
split_index += 1
# get out of here
break
if uitem not in unsorted_list[:split_index]:
# hey we didn't add this item it must be at beginning
unsorted_list.remove(uitem)
unsorted_list.insert(0, uitem)
split_index += 1
# return the sorted list or recursive call with what we have so far
return unsorted_list if split_index == len(unsorted_list) else inplace_insertion_sort(unsorted_list, split_index=split_index)
if __name__ == '__main__':
print(inplace_insertion_sort([23, 42, 4, 16, 8, 15]))
def insertion_sort(unsorted, sorted=list()):
# first iteration we need to start a sorted list with 1 value so we slice it off the unsorted
if not sorted:
sorted = unsorted[:1]
unsorted = unsorted[1:len(unsorted)]
# loop over each item in unsorted list, wrap with list() to copy, so we can pop from unsorted
for uitem in list(unsorted):
# reverse the sorted list to loop over as we compare right to left
for index, sitem in enumerate(reversed(sorted)):
if uitem > sitem:
# insert to sorted list at correct position, index is opposite of what we want so subtract len()
sorted.insert(len(sorted) - index, uitem)
# remove from unsorted so we don't look at it again
unsorted.remove(uitem)
# get out of here
break
if uitem not in sorted:
# hey we didn't add this item it must be at beginning
sorted.insert(0, uitem)
unsorted.remove(uitem)
# return the sorted list or recursive call with what we have so far
return sorted if len(unsorted) <= 0 else insertion_sort(unsorted, sorted)
if __name__ == '__main__':
print(insertion_sort([23, 42, 4, 16, 8, 15]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment