Selection Sort is another simple, in-place sorting algorithm. The main idea is to divide the list into two parts: the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.
The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted part and swapping it with the leftmost element of the unsorted part. This moves the boundary between the sorted and unsorted parts one element to the right.
Here is a function that implements the selection sort algorithm.
def selection_sort(data):
n = len(data)
// Traverse through all array elements
for i in range(n):
// Find the minimum element in the remaining unsorted array
min_idx = i
for j in range(i+1, n):
if data[j] < data[min_idx]:
min_idx = j
// Swap the found minimum element with the first element
data[i], data[min_idx] = data[min_idx], data[i]
// --- Usage ---
my_list = [64, 25, 12, 22, 11]
selection_sort(my_list)
print("Sorted list is:", my_list)
Selection sort's performance is not dependent on the initial order of the data.
The reason it's always O(n²) is that it must iterate through the remaining items to find the minimum in every pass, regardless of whether the list is already sorted or not. It performs fewer swaps than Bubble Sort but has the same time complexity.
Usefulness: Selection sort can be useful in specific situations where memory writes are very expensive, as it minimizes the number of swaps required (at most n-1 swaps).
What is the main goal of each pass in a selection sort?