Python Selection Sort

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

Example

We have an unsorted array-

[4,8,19,2,28,21]

Step 1:

Python Selection Sort 1

Step 2:

Python Selection Sort 2

Step 3:

Python Selection Sort 3

Step 4:

Python Selection Sort 4

Step 5:

Python Selection Sort 5

Step 6:

Python Selection Sort 6

Algorithm

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)

Time Complexity

  • 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.

arr =[4,8,19,2,28,21]

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:
  	print element

Output

2 4 8 19 21 28

Comment below if you have any queries related to above python selection sort tutorial.

The post Python Selection Sort appeared first on The Crazy Programmer.

from The Crazy Programmer https://www.thecrazyprogrammer.com/2017/11/python-selection-sort.html

Unknown's avatar

Author: Just 4 Programmers

Just4Programmers can be described as a private limited company that develops softwares. Kayleigh Baxter who is the current Managing Director established it in early 1997. For several years now, Just4Programmers has been a proud Microsoft Gold Partner. This is to mean that it displays the best expertise and competence with regard to Microsoft technologies and also in relation to being an Amazon Web Services specialist.

Leave a comment

Design a site like this with WordPress.com
Get started