DEV Community

Shahriyar Al Mustakim Mitul
Shahriyar Al Mustakim Mitul

Posted on

DSA by Mitul in C++, Python, and Java : Selection Sort

Selection sort

Here we repeatedly find the minimum element and move it to the sorted part of an array to make unsorted part sorted.

Here is our unsorted array

Image description

First we will divide it in 2 parts. Sorted and Unsorted.

Image description

We will look for every element in the unsorted array to find the minimum value

Image description

It is 1 here.

Then we will swap it

Image description

Then we will assign it in the sorted array

Image description
Again, after the 2nd iteration and swapping we will have:

Image description
After 3rd:

Image description

After the whole iteration , this is what we will be left out

Image description

The benefit of selection sort is : it is a inplace sort and thus we don't need any extra space.
Code for the Selection Sort:

def selectionSort(customList):
    for i in range(len(customList)):
        min_index = i
        for j in range(i+1, len(customList)):
            if customList[min_index] > customList[j]:
                min_index = j
        customList[i], customList[min_index] = customList[min_index], customList[i]
    print(customList)
Enter fullscreen mode Exit fullscreen mode

Complexity Analysis

Image description

When to use Selection sort?

  1. When we have insufficient memory.
  2. Easy to implement.

Why to avoid Selection Sort?
When time is a concern.

Top comments (0)