Python Program for Selection Sort. Diving into the basics sorting algorithm, the selection sort algorithm offers a straightforward approach to rearranging the lists our arrays in a specific order(ascending or descending). This tutorial provides an insightful journey into implementing the selection sort algorithm using Python, Purpose for beginners is to enhance their understanding of algorithmic concepts and Python programming.
Table of Contents
Understanding Selection Sort
Selection sort is a comparison based sorting algorithm that divides the input list into two parts: the sorted part at the beginning and the unsorted part that occupies the rest of the list. The algorithm repeatedly selects the smallest (or largest, depending on the sorting order) Element from the unsorted section and moves it to the end of the sorted section.
Implementing Selection Sort in Python
Defining the Selection Sort Function
Begin defining a Python function named 'selection_sort'
. This function could accept a list 'arr'
as its parameter. This is where the logic for sorting will be encapsulated.
def selection_sort(arr):
#
Implementing the Sorting Logic
The code of the selection sort lies in a nested loop: An outer loop to iterate through the array and an inner loop to find the minimum element in the unsorted function.
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range (i+1,n):
if arr[j]<arr[min_index]:
min_index = j
arr[i],arr[min_index] = arr[min_index],arr[i]
Here is what is happening:
'n'
is the length of the array.- The outer loop runs to each element of the array.
'min_index'
is initially set to the current position'i'
. It represents the index of the smallest element found in the unsorted part.- The inner loop searches for the smallest element by comparing each element with
'arr[min_index]'
- After identifying the smallest element, it swaps with the first element of the unsorted part, effectively growing the sorted part off the list by one element.
Complete the Python Program for Selection Sort
Integrating the sorting logic with the function, we get the complete implementation of selection sort in Python.
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range (i+1,n):
if arr[j]<arr[min_index]:
min_index = j
arr[i],arr[min_index] = arr[min_index],arr[i]
list = [10,21,32,8,5,3]
selection_sort(list)
print("Sorted array")
print(list)
Congratulations!! On successfully implementing the selection sort algorithm in Python. This tutorial guided you through the conceptual understanding and practical application of one of the fundamental sorting algorithms in computer science.
Happy Coding & Learning
See Also
1 thought on “Python Program for Selection Sort”