Before going to the program first let us understand what is Selection Sort?
Selection Sort:
A Selection Sort is a Sorting algorithm that finds the smallest element in the array and swaps with the first element, then with the second element, and continues until the entire array is sorted.
Example: Let us consider the array as given below:
The given array is sorted using Selection Sort as shown below:
Note: Red is the current min.
Yellow is a sorted list.
Blue is the current item.
Now let us see the program code for Selection Sort and understand the code using the Explanation given below.
Program code for Selection Sort:
# Initialize an empty list array = [] n = int(input("Enter the Number of Elements: ")) # Read the elements from the user for i in range(n): element = int(input("Enter the Element: ")) array.append(element) for i in range(n-1): # Initially, assume the first element of the unsorted part as the minimum. min = i for j in range(i+1, n): if array[min] > array[j]: # Update the position of the minimum element if a smaller element is found. min = j # Swap the minimum element with the first element of the unsorted part. if min != i: temp = array[i] array[i] = array[min] array[min] = temp print("The Sorted array in ascending order:", end=" ") for i in range(n): print(array[i], end=" ")
Explanation:
- First the computer reads the number of elements and stores it in the “n” variable using the following lines:
n = int(input("Enter the Number of Elements: "))
- Then using for loop the computer reads the elements and stores it in the variable called “array” using the following lines:
for i in range(n): element = int(input("Enter the Element: ")) array.append(element)
- Then using the nested for loops it finds the smallest element in the array and swaps with the first element, then with the second element, and continues until the entire array is sorted using the following lines:
for i in range(n-1): # Initially, assume the first element of the unsorted part as the minimum. min = i for j in range(i+1, n): if array[min] > array[j]: # Update the position of the minimum element if a smaller element is found. min = j # Swap the minimum element with the first element of the unsorted part. if min != i: temp = array[i] array[i] = array[min] array[min] = temp
- Finally, the sorted array in ascending order is printed on the screen using the following lines:
print("The Sorted array in ascending order:", end=" ") for i in range(n): print(array[i], end=" ")