Skip to content

Instantly share code, notes, and snippets.

@gozeloglu
Last active March 10, 2019 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gozeloglu/2245008d8e3d7e9761a162ce789487db to your computer and use it in GitHub Desktop.
Save gozeloglu/2245008d8e3d7e9761a162ce789487db to your computer and use it in GitHub Desktop.
This is an insertion sort algorithm implemented in Python.
import random as rd
''' Complexity : O(n^2)
In the worst case, the function looks and inverse the elements
(n * (n-1))/2 times. (Reverse order situation)
~1/2N^2 compares and ~1/2N^2 exchanges.
In the best case, the array is sorted. So, we do not make any
inversion operation. We just iterates the array n times and
makes N-1 compares. So, our complexity is O(n).
On average case, insertion sort uses ~1/4N^2 compares and
~1/4N^2 exchanges.
'''
def insertion_sort(arr):
for i in range(len(arr)): # Iterates the all list
tmp = arr[i] # Temporary variable for comparing elements in while loop
j = i
# If index of j is bigger than 1 and tmp variable is lower than
# previous element of the current element
while j > 0 and tmp < arr[j-1]:
arr[j] = arr[j-1] # Changes the elements
j -= 1 # Decrease the index for looking at previous element
arr[j] = tmp
print(arr)
# Test
for _ in range(5):
arr = [rd.randint(0,20) for _ in range(10)]
insertion_sort(arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment