# Choosing the Best Sorting Algorithm

Learn how you can choose a sorting algorithm given the certain requirements and input conditions.

## We'll cover the following

No sorting algorithm is perfect. All have their advantages and disadvantages. Letās discuss them one by one:

## Quicksort

Quicksort is used when a stable sort isnāt required and average-case performance is more critical than worst-case performance. We choose quicksort when the data is random. The quick sort has an average time complexity of $O(nlog(n))$ and worst-case time complexity of $O(nā2āā)$. In addition, quicksort has an $O(log(n))$ additional storage space complexity, the stack space consumed in recursion.

## Merge sort

Merge sort is used when we want a stable sort with a time complexity of O(nlogn). Merge sort is slower than quicksort in general because the merge step involves a lot of copying. Merge sort can be used to merge two sorted linked lists and sort externally.

- Merge sort can be used to merge two sorted linked lists.
- Merge sort can be used for external sorting.

## Heap sort

When we *donāt* want a stable sort and are more concerned about worst-case than average-case performance, it is guaranteed to be $O(nlogn)$. The use of $O(1)$ auxiliary space ensures that we will *not* run out of memory unexpectedly on huge inputs.

## Insertion sort

It is used when we need a stable sort and the input size is small, such as in the base case of quick sort or merge sort. Thus, the time complexity in the worst-case scenario is $O(n^2)$. To compute the actual time taken, it is multiplied by a very modest constant factor. As a result, it outperforms merge-sort and quick sort for smaller input sizes.

## Bubble sort

Letās suppose the data is almost sorted and only two elements are out of place. In the first run, the bubble sort algorithm sorts the data. In the second pass, it checks to verify if everything is sorted before exiting. It just requires two of the arrayās keys.

## Selection sort

The running times for the best, worst, and average cases are all O(nā2āā). Itās only beneficial when we need to do a task quickly. Selection sort is most appropriate in the prototype stage.

## Count sort

Count sort is most appropriate in cases of sorting ranged data.

## Bucket sort

Bucket sort is best to use when our input is uniformly distributed.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.