MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / insert_next

Function insert_next

sorts/recursive_insertion_sort.py:39–68  ·  view source on GitHub ↗

Inserts the '(index-1)th' element into place >>> col = [3, 2, 4, 2] >>> insert_next(col, 1) >>> col [2, 3, 4, 2] >>> col = [3, 2, 3] >>> insert_next(col, 2) >>> col [3, 2, 3] >>> col = [] >>> insert_next(col, 1) >>> col []

(collection: list, index: int)

Source from the content-addressed store, hash-verified

37
38
39def insert_next(collection: list, index: int):
40 """
41 Inserts the '(index-1)th' element into place
42
43 >>> col = [3, 2, 4, 2]
44 >>> insert_next(col, 1)
45 >>> col
46 [2, 3, 4, 2]
47
48 >>> col = [3, 2, 3]
49 >>> insert_next(col, 2)
50 >>> col
51 [3, 2, 3]
52
53 >>> col = []
54 >>> insert_next(col, 1)
55 >>> col
56 []
57 """
58 # Checks order between adjacent elements
59 if index >= len(collection) or collection[index - 1] <= collection[index]:
60 return
61
62 # Swaps adjacent elements since they are not in ascending order
63 collection[index - 1], collection[index] = (
64 collection[index],
65 collection[index - 1],
66 )
67
68 insert_next(collection, index + 1)
69
70
71if __name__ == "__main__":

Callers 1

rec_insertion_sortFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected