Python Selection Sort Example: Sorting a List in Python

Last updated on by Digamber

This tutorial helps you learn about creating an uncomplicated yet powerful method to amplify selection sort in Python using For loop.

We will create two simple functions to sort a data list in ascending and descending order.

Selection Sort

The selection sort algorithm is well known in the programming world. It is a top-notch manifestation of comparison sort.

The selection sort algorithm has O(n²) time complexity, due to which it becomes less effective on large lists, ususally performs worse than the similar insertion sort.

However, we will solve the Selection sort in python because of its uncomplicated behavior. It has the edge over other difficult algorithms for specific cases, especially where auxiliary memory is limited.

Create Selection Sort in Ascending Order

In this step we will learn how to create a selection sort algorithm in Python that sorts data in ascending order. Let’s invoke a brand new function; we name it ascendingSelectionSort().

It takes one parameter as an argument, and that will be the List items, mainly consist of data that needs to be sorted. On a successful selection sorting, it gets us back the sorted list.

Let me put this straight, the core logic we incorporated in this selection sorting algorithm is that. All the unordered list items go through a loop, and the lowest item within the list is grabbed than that element is switched with the first item.

Within this Python selection sort algorithm, we are using atleast two for loops. The first loop is passing over every item from 0 index to n-1.

The second loop is helping to collate every element unless the last item for every iteration.

def ascendingSelectionSort(MyList):
    for i in range(len(MyList) - 1):
        minimum = i
        for j in range( i + 1, len(MyList)):
            if(MyList[j] < MyList[minimum]):
                minimum = j
        if(minimum != i):
            MyList[i], List[minimum] = MyList[minimum], MyList[i]
    return MyList

Selection Sort in Descending Order

Here is the another example in which we are sorting the array data in descending order with selection sort in Python.

def descendingSelectionSort(MyList):
    for i in range(len(MyList) - 1):
        minimum = i
        for j in range(len(MyList)-1,i,-1):
            if(MyList[j] > MyList[minimum]):
                minimum = j
        if(minimum != i):
            MyList[i], MyList[minimum] = MyList[minimum], MyList[i]
    return MyList

Understanding the Selection Sort Complexity

The selection sort algorithm’s time efficiency is quadratic, so a number of sorting techniques have better time complexity than selection sort.

One characteristic which differentiates selection sort from other sorting algorithms is that it performs the least possible number of swaps, n − 1 in the worst case.

Best O(n^2); 

Average O(n^2); 

Worst O(n^2)

Print Selection Sort Result

We are going to declare the key condition, and printing all the result for ascending and descending selection sort algorithm’s result simultaneously.

For that we have to manifest a list, we name this array MyList and it should be synced with the function that we have created earlier.

In the example below we declared the list and printing the sorted list.

if __name__ == '__main__':
    listItems = [4, 5, 3, 7, 4, 6, 2, 8]
    print('Sorted list ascending order:',ascendingSelectionSort(listItems))
    print('Sorted list descending order:',selectionSort_Descending(listItems))

Final Selection Sort in Python Code

Here is the final code that you can rely on:

def ascendingSelectionSort(MyList):
    for i in range(len(MyList) - 1):
        minimum = i
        for j in range( i + 1, len(MyList)):
            if(MyList[j] < MyList[minimum]):
                minimum = j
        if(minimum != i):
            MyList[i], List[minimum] = MyList[minimum], MyList[i]
    return MyList

def descendingSelectionSort(MyList):
    for i in range(len(MyList) - 1):
        minimum = i
        for j in range(len(MyList)-1,i,-1):
            if(MyList[j] > MyList[minimum]):
                minimum = j
        if(minimum != i):
            MyList[i], MyList[minimum] = MyList[minimum], MyList[i]
    return MyList

if __name__ == '__main__':
    listItems = [4, 5, 3, 7, 4, 6, 2, 8]
    print('Sorted list ascending order:', ascendingSelectionSort(listItems))
    print('Sorted list descending order:', descendingSelectionSort(listItems))

Summary

So this was the python selection sort algorithm tutorial. In this example, we tried to teach you both the methods for sorting data in ascending and descending order.