Skip to content

Instantly share code, notes, and snippets.

@jatinsharrma
Created July 26, 2019 10:27
Show Gist options
  • Save jatinsharrma/78eb2763dcffa46051b15583816d1360 to your computer and use it in GitHub Desktop.
Save jatinsharrma/78eb2763dcffa46051b15583816d1360 to your computer and use it in GitHub Desktop.
Insertion Sort
#-------------------------------------------------------------------------------------------------------------------------
#----------------------------------------------INSERTION SORT-------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------------------------
def insertion_sort(unsorted_list):
i = len(unsorted_list)
for num in range(i):
for num1 in range(num):
if unsorted_list[num] < unsorted_list[num1]:
temp = unsorted_list[num]
unsorted_list[num] = unsorted_list[num1]
unsorted_list[num1] = temp
#print(unsorted_list)
print(unsorted_list)
unsorted_list = [9,8,7,6,5,4,3,2,1]
insertion_sort(unsorted_list)
#-----------------------------------------------------------OR--------------------------------------------------------------
def insertion_sort(unsorted_list):
length = len(unsorted_list)
for j in range(1,length):
key = unsorted_list[j]
i = j-1
while i>=0 and unsorted_list[i] > key :
unsorted_list[i+1] = unsorted_list[i]
i = i-1
unsorted_list[i+1] = key
print(unsorted_list)
print(unsorted_list)
unsorted_list = [9,8,7,6,5,4,3,2,1]
insertion_sort(unsorted_list)
#///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#----------------------------------COMPLEXITY = O(n^2)[worst case] / O(n)[Best Case]----------------------------------------
#///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment