Skip to content

Commit bad62ef

Browse files
authored
Add Binary Insertion Sort in Python div-bargali#861
Add Binary Insertion Sort in Python
2 parents 4f995fa + 6edd0d0 commit bad62ef

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
from random import randint
2+
3+
4+
class BinaryInsertionSort:
5+
""" A class to demonstrate Binary Insertion Sort """
6+
7+
def __init__(self, array):
8+
""" Takes the argument array of which is to be sorted """
9+
10+
self.array = array
11+
12+
def __repr__(self):
13+
return f"Array: {self.array}"
14+
15+
def binarySearch(self, array, element, startIdx, endIdx):
16+
""" Performs binary search in the sorted sub-array to insert the next element correctly """
17+
18+
low, high = startIdx, endIdx
19+
20+
while low <= high:
21+
mid = (low + high) // 2
22+
23+
if low == high:
24+
if array[low] == element:
25+
return low + 1
26+
if array[low] > element:
27+
return low
28+
29+
if array[mid] < element:
30+
low = mid + 1
31+
32+
if array[mid] > element:
33+
high = mid - 1
34+
35+
if array[mid] == element:
36+
return mid + 1
37+
38+
if low > high:
39+
return low
40+
41+
def insertionSort(self):
42+
""" Performs Insertion Sort """
43+
44+
print(f"The given array: {self.array}")
45+
46+
for i in range(1, len(self.array)):
47+
currentElement = self.array[i]
48+
j = i - 1
49+
50+
# Searches the location at which the current element is to be inserted
51+
52+
searchedLocation = self.binarySearch(
53+
self.array, currentElement, 0, i-1)
54+
55+
# Inserting the current element in the searched location
56+
while j >= searchedLocation:
57+
self.array[j + 1] = self.array[j]
58+
j -= 1
59+
self.array[j + 1] = currentElement
60+
61+
print(f"The sorted array: {self.array}")
62+
63+
return self.array
64+
65+
66+
array = [randint(1, 100) for i in range(10)]
67+
68+
demo = BinaryInsertionSort(array)
69+
70+
sorted_array = demo.insertionSort()
71+
72+
assert (sorted(array) == sorted_array)

0 commit comments

Comments
 (0)