Implementing Selection Sort Algorithm in Python

The selection sort algorithm approaches the problem of sorting data by dividing and conquering.

The steps of the selection sort are as follows:

Each cell of the array is checked from left to right to determine which has the smallest value. When moving from cell to cell, the lowest value's index that is found is stored in a tracking variable. If a cell contains a value that is even less than the one in the tracking variable, then the tracking variable becomes the new index number.

The cell with the lowest index number is then switched with the cell where the iteration began for the passthrough in progress.

This process continues for as many passthroughs as required to work through all of the indexed positions. This means that as the number of passthroughs increase within the process, the array gets shorter.

First up, here is a Python implementation of selection sort.

""" The code is purposefully not written using Pythonic idioms """

def selection_sort(array):
    for i in range(0, len(array)):
        min_index = i
        for j in range(i + 1, len(array)):
            if array[j] < array[min_index]:
                min_index = j
        array[i], array[min_index] = array[min_index], array[i]
    return array


if __name__ == '__main__':
    random_array = [49, 81, 1, 9, 36, 64, 81, 100, 4, 16, 25]

    sorted_list = selection_sort(random_array)
    print(f'The sorted list is {sorted_list}')

Here is the same implementation in JavaScript

function selectionSort(array) {
  for (let i = 0; i < array.length; i++) {
    var minIndex = i;
    for (let j = i + 1; j < array.length; j++) {
      if(array[j] < array[minIndex]) {
        minIndex = j;
      }
    }
    if (minIndex != i) {
      let temp = array[i];
      array[i] = array[minIndex];
      array[minIndex] = temp;
    }
  }
  return array;
}

randomArray = [49, 81, 1, 9, 36, 64, 81, 100, 4, 16, 25]

sortedList = selectionSort(randomArray);
console.log(`The sorted list is ${sortedList}`);

For those mathematicians amongst you, you will notice that the sorted list produces the first 10 square numbers.

The sorted list is [1, 4, 9, 16, 25, 25, 36, 49, 64, 81, 81, 100]

The selection sort algorithm has a time complexity (or Big-O notation) of O(n²)