Data Structures and Algorithms - Time Complexities
Sorting Algorithm | Best Case | Average Case | Worst Case |
---|---|---|---|
Bubble Sort | |||
Insertion Sort | |||
Selection Sort | |||
Quick Sort | |||
Merge Sort |
The resonse behind each time compexities
Bubble Sort & Selection Sort
For the first run we go through all the n elements For second run we go through n-1 elements For nth run we go through 1 element
So total runs =
Now for time complexity calculation we only focus on the highest degree and we ignore the coefficients. So the time complexity stands here
This is for best case average case and worst case.
Insertion sort - best case
For average and worst case the calculation is same as bubble and selection sort
But for best case, we only check 1 element in the internal loop every time (which is for already sorted array)
Hence the complexity becomes
Quick Sort and Merge sort
In all cases of merge sort and in Best and average case of quicksort we divide the array in two halves each time. And in each layer of the tree of division we go through n elements.
Now the height of a tree is
So the merge of n elements goes times
So the time complexity stands
Quick Sort worst case
In worst case of Quick Sort the time complexity becomes beacuse if we select the worst pivot every time we first time go through n elements then n-1 elements and finally reach 1, which makes the total runs as -
So the time complexity stands here