defbubbleSort(ls): for i inrange(len(ls) - 1): for j inrange(len(ls) - 1 - i): if ls[j] > ls[j + 1]: ls[j], ls[j+1] = ls[j+1], ls[j] return ls
Selection Sort
1 2 3 4 5 6 7 8
defselectSort(ls): for i inrange(len(ls)): mini = i for j inrange(i + 1, len(ls)): if ls[j] < ls[mini]: mini = j ls[mini], ls[i] = ls[i], ls[mini] return ls
Insertion Sort
1 2 3 4 5 6 7
definsertSort(ls): for i inrange(1, len(ls)): for j inrange(i, 0, -1): if ls[j] >= ls[j - 1]: break ls[j], ls[j - 1] = ls[j - 1], ls[j] return ls
Merge Sort
An divide and conquer approch.
If the list is of length 0 or 1, then it is already sorted. Otherwise:
Divide the unsorted list into two sublists of about half the size.
Sort each sublist recursively by re-applying merge sort.
Merge the two sublists back into one sorted list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defmerge(arr1, arr2): res = [] while arr1 and arr2: if arr1[0] <= arr2[0]: res.append(arr1.pop(0)) else: res.append(arr2.pop(0)) res += arr1 if arr1 else arr2 return res
defmergeSort(arr): iflen(arr) < 2: return arr left = arr[:len(arr) // 2] right = arr[len(arr) // 2:] return merge(mergeSort(left), mergeSort(right))
Quick Sort
An divide and conquer strategy. Select a pivot. elements less than pivot, move to the left side, else move to the right side. set the first element as pivot Sort in place:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defpartition(arr, left, right): pivot = arr[right] i = left - 1 for j inrange(left, right): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[right] = arr[right], arr[i+1] return i + 1
replace the root (current largest number) with the last item and reduce the heap size by 1. At this time, the largerst number is sorted and excluded from the heap.
defheapify(arr, n, i): largest = i # Initialize largest as root l = 2 * i + 1 r = 2 * i + 2 # check if any child is greater than root if l < n and arr[largest] < arr[l]: largest = l if r < n and arr[largest] < arr[r]: largest = r # if child greater than node, bubble it up. if largest != i: arr[i], arr[largest] = arr[largest], arr[i] # swap # Heapify the root. heapify(arr, n, largest) defheapSort(arr): n = len(arr) # Build a maxheap. for i inreversed(range(n // 2)): heapify(arr, n, i) # get sorted items one by one for i inreversed(range(1, n)): arr[i], arr[0] = arr[0], arr[i] # swap heapify(arr, i, 0)