Skip to content

Instantly share code, notes, and snippets.

@RJHsiao
Created January 28, 2015 08:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RJHsiao/87bc022625883567e824 to your computer and use it in GitHub Desktop.
Save RJHsiao/87bc022625883567e824 to your computer and use it in GitHub Desktop.
Insertion Sort With Binary Search
#! /usr/bin/env python3
import random
def BinarySearchInsertPoint(searchArray, searchKey):
if len(searchArray) == 0:
return 0
middleIndex = int(len(searchArray) / 2 - 0.5)
print(
"Target Array",
searchArray,
",",
"Insert Key:",
searchKey,
",",
"Middle Index",
middleIndex,
"->",
searchArray[middleIndex],
",",
searchArray[middleIndex],
"<=",
searchKey,
":",
searchArray[middleIndex] <= searchKey
)
if searchArray[middleIndex] <= searchKey:
return middleIndex + 1 + BinarySearchInsertPoint(searchArray[middleIndex+1:], searchKey)
else:
return BinarySearchInsertPoint(searchArray[:middleIndex], searchKey)
def InsertionSort(sortArray):
print("Array:", sortArray)
for i in range(1,len(sortArray)):
if sortArray[i-1] <= sortArray[i]:
continue
print("Phase", i, ":", sortArray)
insertIndex = BinarySearchInsertPoint(sortArray[:i], sortArray[i])
print("Insert Index:", insertIndex)
sortArray[insertIndex],sortArray[insertIndex+1:i+1] = sortArray[i],sortArray[insertIndex:i]
print("Result:", sortArray)
print("===============================================================================================")
print("Finished!")
if __name__ == '__main__':
#sortArray = []
#for x in range(10):
# sortArray.append(random.randrange(10))
sortArray = list(range(10))
random.shuffle(sortArray)
InsertionSort(sortArray)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment