Skip to content

Sorting Algorithms – Selection Sort

It basically compares each elements with the all other elements in the list. If the smallest element is found the first element and the smallest one are swapped. Then, go on with second element to find second smallest one. For detailed information click here.

Time Complexity O(n*n) 

Space complexity O(1)

def selection_sort(original_list):

  #get length of the list
  length = len(original_list)

  #create first loop for checking each element
  for i in range(length):

    #assign the min value's position

    #create second loop for compare each element with the min value#
    for j in range (i+1, length):
      #check whether min value is greater then the other elements
      if original_list[min_value_index] > original_list[j]:

        #if so change min value index
        min_value_index = j

    #swap the elements
    original_list[i], original_list[min_value_index] = 
original_list[min_value_index], original_list[i]

    #print current situation
    print("sorted till index: ", i)

  #print the sorted list
  print("sorted list: ")

#check the list

sorted till index: 0
[2, 3, 14, 5, 7]
sorted till index: 1
[2, 3, 14, 5, 7]
sorted till index: 2
[2, 3, 5, 14, 7]
sorted till index: 3
[2, 3, 5, 7, 14]
sorted till index: 4
[2, 3, 5, 7, 14]
sorted list:
[2, 3, 5, 7, 14]

Published inData SciencePython

Be First to Comment

Leave a Reply

%d bloggers like this: