Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementation of Binary Insertion Sort in Python #1980

Merged
merged 2 commits into from
Mar 9, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions Binary_Insertion_Sort/Binary_Insertion_Sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#sort function

def bin_InsertionSort(lst):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix function name.

for i in range(1, len(lst)):
x = lst[i] # here x is a temporary variable
pos = BinarySearch(lst, x, 0, i) + 1

for j in range(i, pos, -1):
lst[j] = lst[j - 1]

lst[pos] = x


#binary search function for finding the next value

def BinarySearch(array, value, low, high):

if high - low <= 1:
if value < array[low]:
return low - 1
else:
return low

mid = (low + high)//2
if array[mid] < value:
return BinarySearch(array, value, mid, high)
elif array[mid] > value:
return BinarySearch(array, value, low, mid)
else:
return mid

#main function

array = input('Enter the array of numbers: ').split() #enter the values leaving a space between each
array = [int(x) for x in array]
bin_InsertionSort(array)
print('The array after sorting: ', end='')
print(array)

'''
Example:
Input:
Enter the array of numbers: 90 -20 8 11 3
Output:
The array after sorting: [-20, 3, 8, 11, 90]
'''