Selection sort examples in python - python coding

Selection sort examples in python - python coding


Published at - Sep 08, 2021

In this lesson on python coding, we will talk about one of the fundamental algorithms in computer science for sorting Selection Sort. The selection sort algorithm is a very common question for python coding interviews. This article will help if you are preparing for a python coding interview, so let's try to write a simple python program to implement the Selection sort in python.
 
In computer science, selection sort is an in-place comparison sorting algorithm. It has an O(n²) time complexity, which makes it inefficient on large lists, and generally performs worse than the similar insertion sort.
 
These are some highlighted points about binary search algorithm
  • Makes only one exchange for every pass through the list.
  • Time and Space complexity
    • Worst complexity: n^2
    • Average complexity: n^2
    • Best complexity: n^2
    • Space complexity: 1

Algorithm

  • Step 1 − Set MIN to location 0
  • Step 2 − Search the minimum element in the list
  • Step 3 − Swap with value at location MIN
  • Step 4 − Increment MIN to point to next element
  • Step 5 − Repeat until the list is sorted

Selection sort example in python

def selection_sort (num_list):
	for items in range(len(num_list)-1,0,-1):
		max_pos = 0
		for item in range(1,items+1):
			if num_list[max_pos] < num_list[item]:
				max_pos = item
		temp = num_list[max_pos]
		num_list[max_pos] = num_list[item]
		num_list[item] = temp
	return num_list
	
print selection_sort([54,26,93,17,77,31,44,55,20])

This program will print the sorted array as output.

Thank you for reading.





About author

Harendra
Harendra Kanojiya

Hello, I am Harendra Kumar Kanojiya - Owner of this website and a Fullstack web developer. I have expertise in full-stack web development using Angular, PHP, Node JS, Python, Laravel, Codeigniter and, Other web technologies. I also love to write blogs on the latest web technology to keep me and others updated. Thank you for reading the articles.



Related Posts -

Follow Us

Follow us on facebook Click Here

Facebook QR
Scan from mobile
Join our telegram channel Click Here
Telegram QR
Scan from mobile