Selection Sort in python

In this tutorial, you will learn how selection sort work and how to perform selection sort with example.

The selection sort algorithm sorts an array in ascending order by repeatedly finding the minimum element from remaining part and putting it at the beginning.

Example :

    
# python program to sort array using selection sort
def selectionSort( data ):
    n = len( data )
    for i in range( n - 1 ): 
        minValue = i

        for j in range( i + 1, n ):
            if data[j] < data[minValue] :
                minValue = j

        if minValue != i :
            temp = data[i]
            data[i] = data[minValue]
            data[minValue] = temp

    return data

arr = [10,4,3,9,8,2,5,6]
print("Before Sorted :: ",arr)
print("After Sorted :: ",selectionSort(arr))
       

Output :

    
Before Sorted ::  [10, 4, 3, 9, 8, 2, 5, 6]
After Sorted ::  [2, 3, 4, 5, 6, 8, 9, 10]
    

Selection sort breaks the input list in two parts, the sorted part which initially is empty, and the unsorted part, which initially contains the list of all elements. The algorithm then selects the minimum value of all the unsorted file and swaps it with the first unsorted value, and then increases the sorted part by one.


Share your thoughts

Ask anything about this examples