DEV Community

Damian Brdej
Damian Brdej

Posted on

Selection sort algorithm

Let's look at the "top" tab on dev.to, there is a list with the most popular articles on the portal. To display it, first we need to sort all articles by number of views. To do that we can use Selection sort algorithm.

The principle of this algorithm is very simple - we search the list of articles looking for the one with the highest number of views, then we copy it to the first index in the newly created list and remove this item from the old list. We repeat these steps until we have a sorted list.

def findBiggest(arr):
    biggest = arr[0]
    biggest_index = 0

    for i in range(1, len(arr)):
        if arr[i] > biggest:
            biggest = arr[i]
            biggest_index = i
    return biggest_index


def selectionSort(arr):
    newArr = []

    for i in range(len(arr)):
        biggest = findBiggest(arr)
        newArr.append(arr.pop(biggest))
    return newArr


print(selectionSort([51, 32, 63, 2, 101])) # [101, 63, 51, 32, 2]
Enter fullscreen mode Exit fullscreen mode

The algorithm although simple is very slow with a large amount of data, so the dev.to developers surely used something faster. The speed of this algorithm specified in Big O notation is O(n2), since we have to search every element in the list.

More about Big O notation you can read in my previous post here

Top comments (0)