Selection Sort Algorithm
Selection Sort is a simple sorting algorithm that divides the array into two parts:
Divide the array into two parts: sorted and unsorted.
Repeatedly find the smallest element in the unsorted part and move it to the sorted
part by swapping.
Continue until the whole array is sorted.
unsorted =[64, 25, , ]
sorted=[ 11,12,22]
Sorted portion: Initially empty and grows as elements are placed in order.
Unsorted portion: Shrinks as the smallest element is selected and moved to the
sorted portion.
Explanation
Outer loop: Iterates over each position in the array.
Inner loop: Finds the index of the smallest element in the unsorted portion of the
array.
Swap: The smallest element is swapped with the current element at position i.
Example
Input: [64, 25, 12, 22, 11]
Step-by-Step Process:
Initial Array: [64, 25, 12, 22, 11]
[64, 25, 12, 22, 11]
Smallest element in [64, 25, 12, 22, 11] is 11.
Swap 11 with 64.
Array after step 1: [11, 25, 12, 22, 64].
Next Iteration: [25, 12, 22, 64]
Smallest element in [25, 12, 22, 64] is 12.
Swap 12 with 25.
Array after step 2: [11, 12, 25, 22, 64].
Next Iteration: [25, 22, 64]
Smallest element in [25, 22, 64] is 22.
Swap 22 with 25.
Array after step 3: [11, 12, 22, 25, 64].
Final Iteration: [25, 64]
Smallest element in [25, 64] is 25. No swap needed.
Sorted Array: [11, 12, 22, 25, 64].