Selection Sort in Python
In this class, we write a program for selection sort in python.
For Complete YouTube Video: Click Here
Selection Sort
Q1) Write a program to sort the elements in a list using selection sort.
The reader should have some knowledge on selection sort.
All sorting techniques are discussed in our data structures course.
Here we refresh the concept of selection sort and move to implementation.
One should be good in the nested loops concept for implementing selection sort in python. Click here.
Example:
Input: [8,2,5,1,7,4,9,6]
Output: [1,2,4,5,6,7,8,9]
Logic
First iteration
Start from index position zero.
Start from the zero position. Loop on the list and find the minimum element in the list and the index position of the minimum element.
After finding the minimum element position, swap the element present in index position zero with the minimum element.
After completing the first iteration, the minimum element is present in index position zero.
The list look like [1,2,5,8,7,4,9,6].
Now we had a confirmation index position zero is filled with minimum value.
Second iteration
The second iteration starts from index position one.
Identify the minimum element present from index position one to index position n-1. Here n is the number of elements.
Swap the minimum element to the first position.
The same logic is done in the first iteration but starts from the first index position.
After second iteration elements in the list are [1,2,5,8,7,4,9,6].
Continue with n-1 iterations. Each iteration starts with an increment in index position by one.
The program is given below. Please identify the logic for better practice.
Program
elements=[]
n=int(input("enter no of elements"))
for i in range(n):
ele=int(input("enter element"))
elements.append(ele)
for i in range(n-1):
minimum=elements[i]
position=i
for j in range(i,n):
if elements[j]<minimum:
minimum=elements[j]
position=j
temp=elements[i]
elements[i]=elements[position]
elements[position]=temp
print(elements)