Selection Sort is one of the simplest and most intuitive sorting algorithms. It is an in-place, comparison-based algorithm that divides the input list into two parts: the sublist of items already sorted (which is built up from left to right at the front of the list), and the sublist of items remaining to be sorted, occupying the rest of the list.
def selection_sort(arr):
n = len(arr)
for i in range(n):
# Assume the minimum is the first element
min_idx = i
# Traverse the array to find the actual minimum element in the remaining unsorted array
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 is:", sorted_arr)
Sorted array is: [11, 12, 22, 25, 64]
def selection_sort(arr):
selection_sort is defined to take a single list arr as its parameter. n = len(arr)
n stores the length of the input list arr. for i in range(n):
i represents the current position in the sorted portion of the array. min_idx = i
min_idx is initialized to the current index i. This variable will hold the index of the smallest element found in the unsorted portion of the array. for j in range(i+1, n):
i + 1 to n. The index j represents the current position in the unsorted portion of the array. if arr[j] < arr[min_idx]:
min_idx = j
j is smaller than the current minimum element (found at min_idx), then min_idx is updated to j. arr[i], arr[min_idx] = arr[min_idx], arr[i]
i. return arr
arr is returned.arr = [64, 25, 12, 22, 11]
sorted_arr = selection_sort(arr)
print("Sorted array is:", sorted_arr)
arr is sorted using the selection_sort function, and the sorted list is printed.