Selection sort is a simple comparison-based sorting algorithm. It works by repeatedly selecting the minimum element from the unsorted portion of the array and swapping it with the first unsorted element. This process continues until the entire array is sorted. Selection sort has a time complexity of O(n^2) and is not suitable for large data sets.
Consider an array with the following elements:
[64, 25, 12, 22, 11]
To sort this array using selection sort, follow these steps:
Let's apply these steps to the example array:
Below is the pseudo code for the selection sort algorithm:
function selectionSort(array)
n = length(array)
for i = 0 to n - 1 do
minIndex = i
for j = i + 1 to n - 1 do
if array[j] < array[minIndex] then
minIndex = j
end if
end for
swap(array[i], array[minIndex])
end for
end function
Explanation:
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
# Example usage:
array = [64, 25, 12, 22, 11]
print("Original array:", array)
sorted_array = selection_sort(array)
print("Sorted array:", sorted_array) # Output: [11, 12, 22, 25, 64]
This Python program defines a function to perform selection sort on an array. The function iterates through the array, finds the minimum element in the unsorted portion, swaps it with the first unsorted element, and repeats the process until the array is sorted.