Implementing Selection Sort in Python3

Selection Sort is a simple sorting algorithm that finds the smallest element in the array and swaps it with the element in the first position, then finds the second smallest element and swaps it with the element in the second position, and continues in this way until the entire array is sorted.

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