Nov. 22, 2021 python-programming Neeraj Shankar

Selection Sort using Python

Selection sort is a sorting algorithm that selects the smallest element from an unsorted list in each iteration and places that element at the beginning of the unsorted list.

Working of Selection Sort

1. Set the first element as minimum

2. Compare minimum with the second element. If the second element is smaller than minimum, assign the second element as minimum.

3. After each iteration, minimum is placed in the front of the unsorted list. 

4. For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are repeated until all the elements are placed at their correct positions. 

 

arr = [23, 14, 89, 12, 9, 3]
for i in range(len(arr)):
# find the minimum element in the unsorted array
min_index = i
for j in range(i + 1, len(arr)):
if arr[min_index] > arr[j]:
min_index = j

arr[i], arr[min_index] = arr[min_index], arr[i]
# driver code
print("The sorted array is: ")
for i in range(len(arr)):
print("%d" % arr[i]),

Time Complexities:

  • Worst Case Complexity: O(n2)
    If we want to sort in ascending order and the array is in descending order then, the worst case occurs.
  • Best Case Complexity: O(n2)
    It occurs when the array is already sorted
  • Average Case Complexity: O(n2)
    It occurs when the elements of the array are in jumbled order (neither ascending nor descending).

Neeraj Shankar

A result-oriented professional with over 4 years’ experience under different job roles which includes over 2 year of experience with Software Engineer (as also a freelancer)

Comments

Leave a comment