added `sorted_insert.py`

pull/1211/head
Int Fract 2023-06-28 08:05:48 +00:00
parent d3c2184af8
commit caf780f785
1 changed files with 34 additions and 0 deletions

View File

@ -0,0 +1,34 @@
"""
Algorithm Type : Array Insertion
Time Complexity : O(log n)
Space Complexity : O(1)
"""
import math
def sortedIndex(a: list, item):
start = 0
end = len(a)
depth = math.log(len(a) + 1, 2) # the depth of the binary tree
i = 0
while i <= math.ceil(depth): # iterative binary search
mid = (start + end) // 2
if start >= end:
break
if item == a[mid]:
return mid # returns the index of the duplicate element
elif item > a[mid]:
start = mid + 1
else:
end = mid
i += 1
return mid # returns the insertion position for new element
def sortedInsert(a: list, item):
a.insert(sortedIndex(a, item), item)
return a
if __name__ == "__main__":
print(sortedIndex(['a', 'b', 'c', 'd'], 'b')) # 1
print(sortedIndex([0, 1, 2, 3], 1.5)) # 2
print(sortedInsert([0, 1, 2, 3], 1.5)) # [0, 1, 1.5, 2, 3]