Here you’ll learn about python selection sort algorithm with program example.
Selection sort is one of the easiest sorting algorithm out there. In Selection sort, to sort an unsorted array, all we have to do is find the minimum in the array and swap it with the first element in the unsorted array. After each swapping increase the starting index of the array by one.
This is for sorting in ascending order. If we want to sort it into descending order find the maximum instead of minimum and replace with the first element in unsorted array.
Python Selection Sort
We have an unsorted array-
If we have an array of n elements.
Step 1:- set MIN = 0
Step 2:- find minimum element in array
If exists then swap with element at MIN
Step 3:- increase MIN by 1
Step 4:- go to Step 2 until array is sorted (for n-1 times)
- Best Case = O(n)2
- Average Case = O(n)2
- Worst Case = O(n)2
Note: for larger arrays we never use selection sort.
Python Selection Sort Program
Below is the implementation of selection sort in python.
min = 0 #set min = 0
n = len(arr)
while(min <= n-1):
s_i = min
while(s_i <= n-1): #finding minimum
if (arr[s_i] < arr[min]):
arr[min],arr[s_i] = arr[s_i],arr[min] #swapping element at start index with minimum
s_i = s_i+1
min = min+1
for element in arr:
2 4 8 19 21 28
Comment below if you have any queries related to above python selection sort tutorial.