Insertion Sort
Key Idea
This is probably the most intuitive sorting algorithm. If you have played poker before, then this is your go-to algorithm to sort cards in your hand.
Brute Force
def sortIntegers(A: List[int]) -> List[int]:
n = len(A)
if n == 0:
return
sorted_list = []
for num in A:
i = find_insert_position(sorted_list, num)
sorted_list.insert(i, num)
return sorted_list
def find_insert_position(sorted_list: List[int], num: int) -> int:
n = len(sorted_list)
if n == 0:
return 0
for i in range(n):
if sorted_list[i] > num:
return i
return n
time O(n^2) space O(n)
Insertion takes O(n) because copying the array but finding the inserting position is only O(logn) now
Code
need to swap for in-place operations
Time Complexity
The worst case analysis in bubble sort, selection sort, and insertion sort all share a common theme - a halved square (a rugged triangle). That triangle is proportional to O(n^2).
Last updated