What is the time complexity of the selection sort algorithm?

Sorting Algorithms Questions Medium



80 Short 66 Medium 49 Long Answer Questions Question Index

What is the time complexity of the selection sort algorithm?

The time complexity of the selection sort algorithm is O(n^2), where n is the number of elements in the array to be sorted. This means that the time it takes to sort the array increases quadratically with the number of elements.

In selection sort, the algorithm repeatedly finds the minimum element from the unsorted part of the array and swaps it with the element at the beginning of the unsorted part. This process is repeated until the entire array is sorted.

The outer loop of the selection sort algorithm runs n-1 times, as it iterates through each element of the array except the last one. The inner loop, which finds the minimum element, also runs n-1 times in the worst case.

Therefore, the total number of comparisons and swaps performed by the algorithm is approximately (n-1) + (n-2) + ... + 2 + 1, which is equal to (n^2 - n) / 2. Asymptotically, this simplifies to O(n^2).

It is important to note that the time complexity of selection sort remains the same regardless of the initial order of the elements in the array. It does not take advantage of any pre-existing order or partially sorted nature of the array.