Skip to content

Commit

Permalink
Implementation of Binary Insertion Sort in Python (jainaman224#1980)
Browse files Browse the repository at this point in the history
* Create Binary_Insertion_Sort.py
  • Loading branch information
VIJAY07102 authored and Mrunal committed Apr 8, 2020
1 parent 073196f commit 6f73bef
Showing 1 changed file with 46 additions and 0 deletions.
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 Binary_Insertion_Sort(lst):
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]
Binary_Insertion_Sort(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]
'''

0 comments on commit 6f73bef

Please sign in to comment.