Skip to content
Related Articles

Related Articles

Python Program for Selection Sort

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 29 Jul, 2022
View Discussion
Improve Article
Save Article

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 

1) The subarray which is already sorted. 

2) Remaining subarray which is unsorted. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. 

Python3




# Selection sort in Python
# time complexity O(n*n)
#sorting by finding min_index
def selectionSort(array, size):
    
    for ind in range(size):
        min_index = ind
 
        for j in range(ind + 1, size):
            # select the minimum element in every iteration
            if array[j] < array[min_index]:
                min_index = j
         # swapping the elements to sort the array
        (array[ind], array[min_index]) = (array[min_index], array[ind])
 
arr = [-2, 45, 0, 11, -9,88,-97,-202,747]
size = len(arr)
selectionSort(arr, size)
print('The array after sorting in Ascending Order by selection sort is:')
print(arr)

Output

The array after sorting in Ascending Order by selection sort is:
[-202, -97, -9, -2, 0, 11, 45, 88, 747]

Time Complexity:  O(n2).

Auxiliary Space: O(1).

Please refer complete article on Selection Sort for more details!

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!