In insertion sort, the sorting task is similar to that of sorting a deck of cards.
Algorithm:
Stable: yes
Python Implementation
def insertion_sort(arr):
n = len(arr)
for i in range(n):
j = i
while j > 0 and arr[j-1] > arr[j]:
arr[j-1], arr[j] = arr[j], arr[j-1]
j -= 1
Algorithm:
- Start at the beginning
- Find the next element and bring it to its sorted position
- Best: O(n) - when the list is already sorted
- Worst: O(n2) - when required to reverse the entire list
- O(1) - usually no extra space is required
Stable: yes
Python Implementation
def insertion_sort(arr):
n = len(arr)
for i in range(n):
j = i
while j > 0 and arr[j-1] > arr[j]:
arr[j-1], arr[j] = arr[j], arr[j-1]
j -= 1
No comments:
Post a Comment