Introduction:
Selection sort is a simple yet effective sorting algorithm that can be implemented using Python. This tutorial provides a comprehensive guide to implementing the selection sort algorithm. Through practical examples and explanations, you’ll grasp the inner workings of selection sort and how it efficiently organizes elements in ascending order.
Code:
def selection_Sort(list2):
n = len(list2)
for i in range(n): # Traverse through all list elements
min = i
for j in range(i + 1, len(list2)): # The left elements are already sorted in previous passes
if list2[j] < list2[min]:
min = j
if min != i: # Next smallest element is found
list2[min], list2[i] = list2[i], list2[min]
numList = [8, 7, 13, 1, -9, 4]
selection_Sort(numList)
print("The sorted list is:")
for i in range(len(numList)):
print(numList[i], end=" ")
Logic:
- Define the selection_sort function that takes a list list2 as input.
- Get the length of the list n.
- Iterate through each element of the list using an outer loop:
- Initialize min as the current index i.
- Iterate through the remaining unsorted portion of the list using an inner loop.
- Find the index of the minimum element in the unsorted portion.
- Swap the minimum element with the element at index i if necessary.
- The sorted list is printed after the sorting process is complete.
Output:
>>The sorted list is:
>>-9 1 4 7 8 13