MCPcopy
hub / github.com/TheAlgorithms/Python / insort_left

Function insort_left

searches/binary_search.py:100–137  ·  view source on GitHub ↗

Inserts a given value into a sorted array before other values with the same value. It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.insort_left . :param sorted_collection: some ascending sorted collection with comparable items :param item: item

(
    sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1
)

Source from the content-addressed store, hash-verified

98
99
100def insort_left(
101 sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1
102) -> None:
103 """
104 Inserts a given value into a sorted array before other values with the same value.
105
106 It has the same interface as
107 https://docs.python.org/3/library/bisect.html#bisect.insort_left .
108
109 :param sorted_collection: some ascending sorted collection with comparable items
110 :param item: item to insert
111 :param lo: lowest index to consider (as in sorted_collection[lo:hi])
112 :param hi: past the highest index to consider (as in sorted_collection[lo:hi])
113
114 Examples:
115 >>> sorted_collection = [0, 5, 7, 10, 15]
116 >>> insort_left(sorted_collection, 6)
117 >>> sorted_collection
118 [0, 5, 6, 7, 10, 15]
119 >>> sorted_collection = [(0, 0), (5, 5), (7, 7), (10, 10), (15, 15)]
120 >>> item = (5, 5)
121 >>> insort_left(sorted_collection, item)
122 >>> sorted_collection
123 [(0, 0), (5, 5), (5, 5), (7, 7), (10, 10), (15, 15)]
124 >>> item is sorted_collection[1]
125 True
126 >>> item is sorted_collection[2]
127 False
128 >>> sorted_collection = [0, 5, 7, 10, 15]
129 >>> insort_left(sorted_collection, 20)
130 >>> sorted_collection
131 [0, 5, 7, 10, 15, 20]
132 >>> sorted_collection = [0, 5, 7, 10, 15]
133 >>> insort_left(sorted_collection, 15, 1, 3)
134 >>> sorted_collection
135 [0, 5, 7, 15, 10, 15]
136 """
137 sorted_collection.insert(bisect_left(sorted_collection, item, lo, hi), item)
138
139
140def insort_right(

Callers

nothing calls this directly

Calls 2

bisect_leftFunction · 0.85
insertMethod · 0.45

Tested by

no test coverage detected