Created
January 28, 2015 08:04
-
-
Save RJHsiao/87bc022625883567e824 to your computer and use it in GitHub Desktop.
Insertion Sort With Binary Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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