Selection Sort in Python
In this tutorial, we will implement the
selection sort algorithm in Python. It is quite
straightforward algorithm using the less
swapping.
In this algorithm, we select the smallest
element from an unsorted array in each pass
and swap with the beginning of the unsorted
array. This process will continue until all the
elements are placed at right place. It is simple
and an in-place comparison sorting algorithm.
Working of Selection Sort
The following are the steps to explain the
working of the Selection sort in Python.
Let's take an unsorted array to apply the
selection sort algorithm.
Step - 1: Get the length of the array.
length = len(array) → 6
Step - 2: First, we set the first element as
minimum element.
Step - 3: Now compare the minimum with
the second element. If the second element is
smaller than the first, we assign it as a
minimum.
Again we compare the second element to the
third and if the third element is smaller than
second, assign it as minimum. This process
goes on until we find the last element.
Step - 4: After each iteration, minimum
element is swapped in front of the unsorted
array.
Step - 5: The second to third steps are
repeated until we get the sorted array.
Example : [Link]
Selection Sort Algorithm
selectionSort(array, size)
repeat (size - 1) times
set the first unsorted element as the minimum
for each of the unsorted elements
if element < currentMinimum
set element as new minimum
swap minimum with first unsorted position
end selectionSort
# Selection sort in Python
def selectionSort(array, size):
for step in range(size):
min_idx = step
for i in range(step + 1, size):
# to sort in descending order,
change > to < in this line
# select the minimum element in
each loop
if array[i] < array[min_idx]:
min_idx = i
# put min at the correct position
(array[step], array[min_idx]) =
(array[min_idx], array[step])
data = [-2, 45, 0, 11, -9]
size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)