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
min_value_index=i
#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(original_list)
#print the sorted list
print("sorted list: ")
print(original_list)
#check the list
selection_sort([5,3,14,2,7])
Output:
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]
Be First to Comment