For example:
Let's take the following array: [3, 1, 5, 2]
Step 1: The smallest element is 1. We swap it with the first element.
Result: [1, 3, 5, 2]
Step 2: The second smallest is swapped with the second element.
Result: [1, 2, 5, 3]
Step 3: The third smallest is swapped with the third element.
Result: [1, 2, 3, 5]
The array is now sorted.
Note: The algorithm is efficient for smaller lists, but very inefficient for larger lists.
Selection Sort in Python3:
def selection_sort(arr):
for k in range(len(arr)):
min_index = k # smallest element
for j in range(k + 1, len(arr)):
if arr[min_index] > arr[j]:
min_index = j
arr[k], arr[min_index] = arr[min_index], arr[k]
nums = [64, 25, 12, 22, 11]
selection_sort(nums)
print(nums)
0 Comments