Selection Sort
Find the minimum element in the sequence and swap it with the element at the current position. Repeat this process for all elements until the entire sequence is sorted.
- First, find the minimum (or maximum) element in the unsorted sequence and store it at the beginning of the sorted sequence.
- Continue to find the minimum (or maximum) element from the remaining unsorted elements and place it at the end of the sorted sequence.
- Repeat step 2 until all elements are sorted.
Code Implementation
::: code-tabs
@tab Java
public class SelectionSort implements IArraySort {
@Override
public int[] sort(int[] sourceArray) throws Exception {
int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
// Total of N-1 comparison rounds required
for (int i = 0; i < arr.length - 1; i++) {
int min = i;
// Number of comparisons per round: N-i
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
// Record the index of the minimum element found so far
min = j;
}
}
// Swap the found minimum element with the element at position i
if (i != min) {
int tmp = arr[i];
arr[i] = arr[min];
arr[min] = tmp;
}
}
return arr;
}
}
@tab JavaScript
function selectionSort(arr) {
var len = arr.length;
var minIndex, temp;
for (var i = 0; i < len - 1; i++) {
minIndex = i;
for (var j = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) { // Find the smallest number
minIndex = j; // Save the index of the smallest number
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
return arr;
}
@tab Python
def selectionSort(arr):
for i in range(len(arr) - 1):
# Record the index of the smallest number
minIndex = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[minIndex]:
minIndex = j
# If i is not the smallest number, swap i with the smallest number
if i != minIndex:
arr[i], arr[minIndex] = arr[minIndex], arr[i]
return arr
@tab Go
func selectionSort(arr []int) []int {
length := len(arr)
for i := 0; i < length-1; i++ {
min := i
for j := i + 1; j < length; j++ {
if arr[min] > arr[j] {
min = j
}
}
arr[i], arr[min] = arr[min], arr[i]
}
return arr
}
@tab PHP
function selectionSort($arr){
$len = count($arr);
for ($i = 0; $i < $len - 1; $i++) {
$minIndex = $i;
for ($j = $i + 1; $j < $len; $j++) {
if ($arr[$j] < $arr[$minIndex]) {
$minIndex = $j;
}
}
$temp = $arr[$i];
$arr[$i] = $arr[$minIndex];
$arr[$minIndex] = $temp;
}
return $arr;
}
:::