Amazing-Python-Scripts
73 строки · 3.0 Кб
1"""
2Insertion Sort
3Insertion sort is an simple sorting algorithm that builds the final sorted array one item at a time
4Benefits of Insertion Sort
5Simple Implementation
6Efficient for quite small data sets
7Adaptive: efficient for data sets that are already substantially sorted
8Stable: does not change relative order of elements with equal keys
9In-Place: only requires a constant amount O(1) of additional extra space
10Online: can sort a list as it receives it
11Traditional Approach
12Let unsorted array be Uarr and Sorted array be Sarr
13Create a sorted array namely 'Sarr'
14Put i(th) element from Uarr to Sarr
15put (i+1)th element in Sarr such that the array is still sorted
16put(i+2)th element such that array is still sorted by comparing and shuffling the elements, if required
17Effective Approach
18Take a pointer at index[1] {considering index[0] is sorted}
19Let everything at left of the pointer be sorted
20compare the current pointed element with the elements of sorted side (i.e. left side)
21If CurrentElement < elements at sorted array: insert current element at appropriate place of sorted array
22If CurrentElement > elements at sorted array: repeat above processes until array is sorted
23
24For instance,
25Uarr: 2 5 8 1 3 4
262 5 8 1 3 4 2,5
272 5 8 1 3 4 5,8
282 5 8 1 3 4 8,1
291 2 5 8 3 4 8,3
301 2 3 5 8 4 8,4
311 2 3 4 5 8 Sarr
32
33Worst-Case Performance O(n^2)-{Comparisons} and O(n^2)-{Swaps}
34Best-Case Performance O(n)-{Comparisons} and O(1)-{Swaps}
35Average Performance O(n^2)-{Comparisons} and O(n^2)-{Swaps}
36Worst-caseSpace Performance O(n)-{Comparisons} and O(1)-{Auxiliary}
37
38"""
39
40
41def InsertionSort(elements):
42# starting with the 2nd element {index[1]}
43for i in range(1, len(elements)):
44pointer = elements[i] # current element named as pointer
45# left element of pointer {index[current] - 1 = elements[left]}
46j = i - 1
47# compare current element (pointer) to sorted array (j)
48# iterate between j to index[0] and continue until elements of j > pointer
49while j >= 0 and pointer < elements[j]:
50# swapped left element to right element
51elements[j + 1] = elements[j]
52j = j - 1 # same as j--
53# when loop is terminated, pointer will be assigned to next element
54# increase pointer value and repeat until array is sorted
55elements[j + 1] = pointer
56
57
58if __name__ == '__main__':
59elements = [2, 5, 8, 1, 3, 4]
60InsertionSort(elements)
61print(elements)
62# test cases
63tests = [
64[11, 9, 29, 7, 2, 15, 28], # worst-case scenario
65[3, 7, 9, 11], # sorted list
66[25, 22, 21, 10], # DESC-sorted list
67[], # empty list
68[6] # single element list
69]
70
71for elements in tests:
72InsertionSort(elements)
73print(f"Sorted array: {elements}")
74