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
First we will divide it in 2 parts. Sorted and Unsorted.
We will look for every element in the unsorted array to find the minimum value
It is 1 here.
Then we will swap it
Then we will assign it in the sorted array
Again, after the 2nd iteration and swapping we will have:
After the whole iteration , this is what we will be left out
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)
Complexity Analysis
When to use Selection sort?
- When we have insufficient memory.
- Easy to implement.
Why to avoid Selection Sort?
When time is a concern.
Top comments (0)