DEV Community

Damian Brdej
Damian Brdej

Posted on

2 1

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay