Selection Sort is a simple comparison-based sorting algorithm. It works by repeatedly selecting the smallest (or largest, depending on the order) element from the unsorted part of the array and placing it in its correct position in the sorted part of the array. The algorithm performs in-place sorting, meaning it doesn't require additional memory outside of the input array.
The basic idea of Selection Sort is to divide the array into two parts:
In each iteration, Selection Sort finds the smallest (or largest) element from the unsorted portion of the array and swaps it with the first unsorted element, effectively growing the sorted portion.
for i = 0 to n-1
min_index = i
for j = i+1 to n
if array[j] < array[min_index]
min_index = j
swap array[i] with array[min_index]
0 to n-1, where n is the size of the array. This loop controls the boundary of the sorted portion of the array.i+1 to n to find the smallest element in the unsorted portion.i).Let's walk through an example to better understand how Selection Sort works.
Suppose we have an array:
[64, 25, 12, 22, 11]
The unsorted portion is [64, 25, 12, 22, 11].
The smallest element in the unsorted portion is 11 (index 4).
Swap 11 with the first element (index 0), so the array becomes:
[11, 25, 12, 22, 64]
The unsorted portion is [25, 12, 22, 64].
The smallest element is 12 (index 2).
Swap 12 with the second element (index 1), so the array becomes:
[11, 12, 25, 22, 64]
The unsorted portion is [25, 22, 64].
The smallest element is 22 (index 3).
Swap 22 with the third element (index 2), so the array becomes:
[11, 12, 22, 25, 64]
The unsorted portion is [25, 64].
The smallest element is 25 (index 3).
Swap 25 with the fourth element (index 3), no change in the array.
[11, 12, 22, 25, 64]
[64], and it's already sorted.The array is now fully sorted:
[11, 12, 22, 25, 64]
Explanation:
Explanation:
Selection Sort is a very simple but inefficient algorithm, particularly for large arrays. It is more suitable for small datasets or as a teaching tool to understand basic sorting principles. For practical use on large datasets, more efficient algorithms like Quick Sort, Merge Sort, or Heap Sort are preferred.
Open this section to load past papers