Selection Sort in Python
Here you will learn the program code of selection sort in python programming.
To write a Python program for selection sort, you need to understand how to repeatedly find the minimum element from an unsorted portion of the list and place it at the beginning.
What is selection sort in python
Selection sort is an algorithm used to sort elements in an array. It works by selecting the smallest element of the array and placing it at the beginning of the array. It then selects the next smallest element and places it after the previously selected element. This process is repeated until all elements are sorted.
Selection sort in python program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #Python Selection Sort program def selectionSort(arr): for i in range(len(arr)): min_idx = i for j in range(i+1, len(arr)): if arr[min_idx] > arr[j]: min_idx = j arr[i], arr[min_idx] = arr[min_idx], arr[i] arr = [] print("Enter 5 numbers ") for i in range(5): item = int(input('Input item : ')) arr.append(item) selectionSort(arr) print ("Sorted array are the following....") for i in range(len(arr)): print("%d" %arr[i]), |
Output
Enter 5 numbers
Input item : 3
Input item : 4
Input item : 2
Input item : 1
Input item : 6
Sorted array are the following….
1
2
3
4
6
Check out our other Python Programming Examples