Selection sort in python

Python program for Selection sort. Here mentioned other language solution.

#  Python 3 program for selection sort
class MySort :
	#  Swap the list element
	def swap(self, arr, x, y) :
		#  x and y are index of list
		temp = arr[x]
		arr[x] = arr[y]
		arr[y] = temp
	
	def selectionSort(self, arr, n) :
		min = 0
		i = 0
		#  Execute loop from 0..n
		while (i < n) :
			#  Get current index
			min = i
			j = i + 1
			while (j < n) :
				if (arr[min] > arr[j]) :
					#  Get the minimum element index
					min = j
				j += 1
			
			if (i != min) :
				#  Swap minimum element at i index
				self.swap(arr, i, min)
			
			i += 1
		
	
	#  Display list elements
	def display(self, arr, n) :
		i = 0
		while (i < n) :
			#  Display element value
			print("", arr[i], end = "")
			i += 1
		
		print(end = "\n")
	

def main() :
	task = MySort()
	#  Array of integer elements
	arr = [8, 2, 3, 8, 1, 3, 73, 121, 54, 23, 84, 13, 67, 23, 52]
	#  Get the size of list
	n = len(arr)
	print(" Before Sort :")
	task.display(arr, n)
	#  Test
	task.selectionSort(arr, n)
	print(" After Sort :")
	task.display(arr, n)

if __name__ == "__main__": main()

Output

 Before Sort :
 8 2 3 8 1 3 73 121 54 23 84 13 67 23 52
 After Sort :
 1 2 3 3 8 8 13 23 23 52 54 67 73 84 121


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved