8

Wiki has a good cheat sheet, but however it does not involve no. of comparisons or swaps. (though no. of swaps is usually decides its complexity). So I created the following. Is the following info is correct ? Please let me know if there is any error, I will correct it.

Insertion Sort:

  • Average Case / Worst Case : $\Theta(n^2)$ ; happens when input is already sorted in descending order
  • Best Case : $\Theta(n)$ ; when input is already sorted
  • No. of comparisons : $\Theta(n^2)$ in worst case & $\Theta(n)$ in best case
  • No. of swaps : $\Theta(n^2)$ in worst/average case & $0$ in Best case

Selection Sort:

  • Average Case / Worst Case / Best Case: $\Theta(n^2)$
  • No. of comparisons : $\Theta(n^2)$
  • No. of swaps : $\Theta(n)$ in worst/average case & $0$ in best case At most the algorithm requires N swaps, once you swap an element into place, you never touch it again.

Merge Sort :

  • Average Case / Worst Case / Best case : $\Theta(nlgn)$ ; doesn't matter at all whether the input is sorted or not
  • No. of comparisons : $\Theta(n+m)$ in worst case & $\Theta(n)$ in best case ; assuming we are merging two array of size n & m where $n<m$
  • No. of swaps : No swaps ! [but requires extra memory, not in-place sort]

Quick Sort:

  • Worst Case : $\Theta(n^2)$ ; happens input is already sorted
  • Best Case : $\Theta(nlogn)$ ; when pivot divides array in exactly half
  • No. of comparisons : $\Theta(n^2)$ in worst case & $\Theta(nlogn)$ in best case
  • No. of swaps : $\Theta(n^2)$ in worst case & $0$ in best case

Bubble Sort:

  • Worst Case : $\Theta(n^2)$
  • Best Case : $\Theta(n)$ ; on already sorted
  • No. of comparisons : $\Theta(n^2)$ in worst case & best case
  • No. of swaps : $\Theta(n^2)$ in worst case & $0$ in best case

Linear Search:

  • Worst Case : $\Theta(n)$ ; search key not present or last element
  • Best Case : $\Theta(1)$ ; first element
  • No. of comparisons : $\Theta(n)$ in worst case & $1$ in best case

Binary Search:

  • Worst case/Average case : $\Theta(logn)$
  • Best Case : $\Theta(1)$ ; when key is middle element
  • No. of comparisons : $\Theta(logn)$ in worst/average case & $1$ in best case

  1. I have considered only basic searching & sorting algorithms.
  2. It is assumed above that sorting algorithms produce output in ascending order
  3. Sources : The awesome CLRS and this Wiki
Maharaj
  • 274
  • 3
  • 18
avi
  • 1,473
  • 4
  • 24
  • 39

1 Answers1

-2

For general algorithm of bubble sort worst case comparisons are $\Theta(n^2)$ But for special case algorithm where in you add a flag to indicate that there has been a swap in previous pass. If there were no swaps then we come out of the loop since array is already sorted. In this case comparisons are $n$ not 0.

For Quick sort you have mentioned that worst case swaps are $n^2$. Well worst case scenario for quick sort is when all elements are in sorted order thus there won't be any swaps so it should be zero.