Selection Sort
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.
import random
Array=[]
SortedArray=[]
n=int (random.uniform(1,10))
for i in range(0,n,1):
Array.append(int(random.uniform(1,250)))
SortedArray=Array
def SelectionSort(SortedArray):
step=1
for i in range(len(SortedArray)-1):
for j in range(i+1,len(SortedArray)):
print("Step:",step,"(input) | i= ",i," | j=",j," | ",SortedArray)
if SortedArray[j]<SortedArray[i]:
tmp = SortedArray[i]
SortedArray[i] = SortedArray[j]
SortedArray[j] = tmp
print("Step:",step,"(output)| i= ",i," | j=",j," | ",SortedArray)
step = step +1
print("\n SortedArray = ",end = "")
for i in range(len(SortedArray)):
if i+1 ==len(SortedArray):
print(SortedArray[i],end = "")
else:
print(SortedArray[i],end = ",")SelectionSort(SortedArray)
Also if you wanna pure python code without explanation you can look:
# Python program for implementation of Selection
# Sortimport sys
A = [64, 25, 12, 22, 11]# Traverse through all array elements
for i in range(len(A)):#Find the minimum element in remaining unsorted array min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j#Swap the found minimum element with the first element A[i], A[min_idx] = A[min_idx], A[i]#Driver code to test aboveprint ("Sorted array")
for i in range(len(A)):
print("%d" %A[i])
Also you can look : https://www.youtube.com/watch?v=xWBP4lzkoyM