Selection Sort
def selection_sort(arr):
n = len(arr)
for i in range(n):
# Find the minimum element in the unsorted portion
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
# Swap the found minimum element with the first element
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
# Example usage:
arr = [64, 25, 12, 22, 11]
sorted_arr = selection_sort(arr)
print("Sorted array:", sorted_arr)
# Sorted array: [11, 12, 22, 25, 64]
Complexity
Type | Complexity |
---|---|
Time | Worst: O(n^2) |
Space | Worst: O(1) |
Stability
Not stable