Selection Sort:
- Consider an unsorted array A = [5,2,3,1,6]. In Selection Sort, let us take another empty array B.
- We will then take the minimum element from A and put it in B and keep on repeating this step till array A is empty.
- Now all the elements in array B are sorted. We can then copy these elements to array A.
- Problem: This method will need an extra space for another array B. This is not an in-place algorithm. In-Place Algorithm takes constant amount of extra memory.
Selection Sort (In-Place):
- Consider an unsorted array A = [5,3,2,1,6]. Here the first minimum element is 1 which is A[3] so we will exchange it with A[0].
- It will look like A = [1,3,2,5,6]. Now find the second minimum element from 1 to end of array which is 2 i.e.A[2], replace it with A[1].
- Repeat the process till the end of array.
def SelectionSort(A,n):
for i in range(n):
iMin = i
for j in range(i+1,n):
if A[j]<A[iMin]:
iMin = j
temp = A[i]
A[i] = A[iMin]
A[iMin] = temp
return A
A = [5,3,4,2,1]
ans = SelectionSort(A,len(A))
print ans