Sorting

Comparison Sorting

Selection Sort

Bubble Sort

Insertion Sort

Merge Sort

Heap Sort

Quick Sort

Best

O(n^2)

O(n)

O(n)

O(n log n)

O(n log n)

O(n log n)

Average

O(n^2)

O(n^2)

O(n^2)

O(n log n)

O(n log n)

O(n log n)

Worst

O(n^2)

O(n^2)

O(n^2)

O(n log n)

O(n log n)

O(n^2)

Worst(space)

O(1)

O(1)

O(1)

O(n)

O(1)

O(log n)

Selection Sort

  1. Find the smallest element in array[1,...,n] and swap into index 0; 每一次从后面找最小的数,放到当前index里。

  2. Find the smallest element in array[2,...,n] and swap into index 1;

  3. Keep going until all elements are sorted.

Time Complexity:

  • Best: O(n^2)

  • Worst: O(n^2)

Bubble Sort

  1. Go through all elements, compare it with the one after it.If current index has greater value, swap. 每次和后一个数对比,如果大,就交换。每次把最大的数放后面。

  2. Repeats until all elements are sorted.

Time complexity:

  • Best: O(n) - if nearly sorted

  • Worst: O(n^2)

Insertion Sort

  • Go through all elements, compare it with the one before it, keep going until it's larger or first of array. 每次往前比较,直到它比前面的数字都大或者前面没数字了。

Merge Sort

  1. Divide: split partition into two sequence, about n/2 elements each

  2. Conquer: merge two sorted subsequences into a sorted sequence

Complexity:

  • Time complexity: O(n log n)

  • Space complexity: O(n) – store partitions for merge

Heap Sort

  1. Build a internal max/min heap

  2. For every node from leaf to root, swap with current root, check if it's violates the max/min heap property, if does, perform heapify.

Time complexity: O(n log n)

Quick Sort

  1. Select a pivot, usually first or last element in the array

  2. Divide: partition array into 2 subarrays s.t. elements in the lower part <= elements in the higher part.

  3. Conquer: recursively sort the 2 subarrays

Time complexity: O(n log n) – almost in-place

Linear Sorting

Counting Sort

Radix Sort

Bucket Sort

Last updated

Was this helpful?