Selection Sort Implementation in Python

We all know that a Selection Sort is a sorting algorithm. You can find the implementation code of this algorithm is everywhere. But I want to organize this on my site.

The complexity of this algorithm.

Worst Complexity: O( n^2 )
Average Complexity: O( n^2 )
Best Complexity: O( n^2 )
Space Complexity: O( 1 )

def selection_sort(lst):
	for i in range(len(lst)):
		min_index = i
		for j in range(i + 1, len(lst)):
			if lst[min_index] > lst[j]:
				min_index = j
		
		if lst[min_index] != lst[i]:
			temp = lst[i]
			lst[i] = lst[min_index]
			lst[min_index] = temp
	
	return lst

print(selection_sort([5, 2, 1, 3, 6, 4, 7])) # Output = [1, 2, 3, 4, 5, 6, 7]
Scroll to Top