SELECTION SORT

 Selection sort is a sorting algorithm where a list/array of items are sorted by repeatably  iterating through the list. 

In each loop we pick the lowest value and keep it the beginning of the list.  Thus during looping it virtually creates two lists. One with sorted list and the another with the remaining unsorted list.


Here is an example:

Unsorted list: [54, 89, 22, 15, 67]

First iteration: We traverse through the whole list and find the lowest value here its 15. So we pick 15 and swap it with the value in the first position so following is the result after first iteration

[15, 89, 22, 54, 67]

Second iteration: We start traversing through the whole list from second position and find the lowest value here its 22. So we pick 22 and swap it with the value in the second position so following is the result after second iteration

[15,  22, 89, 54, 67]

Third iteration: We start traversing through the whole list from third position and find the lowest value here its 54. So we pick 54 and swap it with the value in the third position so following is the result after third iteration

[15,  22, 5489, 67]

Fourth iteration: We start traversing through the whole list from fourth position and find the lowest value here its 67. So we pick 67 and swap it with the value in the fourth position so following is the result after fourth iteration

[15,  22, 54, 67, 89]

Thus the list is sorted. 


Let's write a python program to implement the above.


list_array = [54, 89, 22, 15, 67]

list_size = len(list_array)

for index in range(list_size):

min_index = index

for j in range(index + 1, list_size):

if list_array[j] < list_array[min_index]:

min_index = j

list_array[index], list_array[min_index] = list_array[min_index], list_array[index]

print("Sorted list:", list_array) 


Output:

Sorted list: [15, 22, 54, 67, 89]



Comments

Popular posts from this blog

IDEs for Python Beginners