Algorithm

Take a list of length

We can iterate through the list, and for every iteration, pick the next smallest element to place at the front of our list. So, for every iteration , we find the smallest element and swap it with the element at the index.

  1. For the first iteration (swap 1 with 5),
  2. For the second iteration (swap 2 with itself),
  3. For the third iteration (swap 3 with 5),

We are done!

Every iteration, we are essentially β€œpicking” the next smallest element to place in the next position!

Pseudocode

Pseudocode for Selection Sort is given below.

def selection_sort(array):
    # for every iteration, we pick the next smallest
    # element to place at i
    for i in range(0, len(array) - 1):
        # find the ith smallest element
        min_index = i
        
        for j in range(i + 1, len(array)):
            if array[j] < array[min_index]:
               min_index = j
 
        # place next smallest element at index i
        temp = array[i]
        array[i] = array[min_index]
        array[min_index] = temp

Let’s find the time complexity of Selection Sort. Let denote the amount of time it takes for line 9-10 to run. Then, we can find the of Selection Sort using the number of times runs (as it has the most significant contribution to the runtime).

Note that Selection Sort will always take the same amount of time!

Additionally we find,

  • The auxilliary memory to be .
  • The algorithm is not stable, as our selection can swap and change the relative order of equal elements.
  • The algorithm to be in-place, as no additional memory is used.