Skip to content

Instantly share code, notes, and snippets.

@njacobs5074
Created October 12, 2019 17:12
Show Gist options
  • Select an option

  • Save njacobs5074/4af3f87f8273cd3a0a43ab4cfd9b06f0 to your computer and use it in GitHub Desktop.

Select an option

Save njacobs5074/4af3f87f8273cd3a0a43ab4cfd9b06f0 to your computer and use it in GitHub Desktop.
Simple Insertion Sort in Python
import random
import sorting
# Color Code -- 2019-10-12
# Create 20 random number from -10 to +10
my_randoms = random.sample(xrange(-10, 11), 20)
print("20 random numbers:")
print(my_randoms)
# Sort the random numbers above and print them out.
print("Sorted:")
print(sorting.insert_sort(my_randoms))
print(sorting.insert_sort([-2, -4, 3, 2, 1]))
print("\nSorted numbers w/duplicates")
print(sorting.insert_sort([0, 1, 2, 3, 3]))
print(sorting.insert_sort([1, 2]))
def insert_sort(array_of_numbers):
i = 1
while i < len(array_of_numbers):
j = i
while j > 0 and array_of_numbers[j - 1] > array_of_numbers[j]:
tmp = array_of_numbers[j - 1]
array_of_numbers[j - 1] = array_of_numbers[j]
array_of_numbers[j] = tmp
j = j - 1
i = i + 1
return array_of_numbers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment