Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion and placing it at the beginning. The algorithm divides the array into sorted and unsorted portions, gradually expanding the sorted section. It has a time complexity of O(n squared) and uses constant space, making it an in-place sorting algorithm.
Selection sort is a fundamental sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the array and placing it at the beginning. Let's see how it transforms an unsorted array into a sorted one.
Let's walk through selection sort step by step using the array 64, 25, 12, 22, 11. In the first iteration, we find the minimum element 11 and swap it with the first element. The red indicator shows the current minimum, blue shows the element being compared.
Here's the complete C++ implementation of selection sort. The algorithm uses two nested loops: the outer loop runs n-1 times, and the inner loop finds the minimum element in the remaining unsorted portion. The time complexity is O(n²) as we have nested loops, but the space complexity is O(1) since we only use a constant amount of extra space.
Selection sort has a time complexity of O(n²) in all cases - best, average, and worst. This is because regardless of the input, we always perform the same number of comparisons. The space complexity is O(1) as it sorts in-place. While simple to implement, selection sort is not stable and performs poorly on large datasets compared to more advanced algorithms like merge sort or quick sort.
Here's the complete C++ implementation of selection sort. The algorithm uses nested loops where the outer loop iterates through each position, and the inner loop finds the minimum element in the remaining unsorted portion. The swap function exchanges the minimum element with the current position. This implementation has O(n²) time complexity and O(1) space complexity, making it an in-place sorting algorithm.