Table of Contents

Selection Sort in Python

Example Description
Discover the selection sort algorithm using Python. Learn how to implement selection sort step by step with practical examples. Explore an efficient sorting technique that arranges elements in ascending order, and witness the algorithm in action through clear code examples.

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:

  1. Define the selection_sort function that takes a list list2 as input.
  2. Get the length of the list n.
  3. Iterate through each element of the list using an outer loop:
  4. Initialize min as the current index i.
  5. Iterate through the remaining unsorted portion of the list using an inner loop.
  6. Find the index of the minimum element in the unsorted portion.
  7. Swap the minimum element with the element at index i if necessary.
  8. The sorted list is printed after the sorting process is complete.

Output:

>>The sorted list is:

>>-9 1 4 7 8 13