This article may contain affiliate links. If you buy some products using those links, I may receive monetary benefits. See affiliate disclosure here
Selection Sorting is one of the easiest and simplest of all sorting algorithms. It starts from the beginning of the array, comparing each item with the rest of the items, swaps them if required to bring the lowest (or highest if in descending order) item to the beginning.
In the next iteration, it moves to the second item, finding the second lowest item, and so on, until it reaches the last item.
Here is a program written in C that sorts a given array in ascending order.
Selection Sort in C
#include <stdio.h>
void printArray(int numbers[], int n) {
int i;
for(i=0; i<n; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
}
void sortArray(int numbers[], int n) {
int i, j, temp;
for (i=0; i<n-1; i++) {
for (j=i+1; j<n; j++) {
if(numbers[j] < numbers[i]) {
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
}
int main() {
int numbers[] = {325, 135, 25, 1025, 68, 17, 512, 468};
int length;
int n = sizeof(numbers) / sizeof(numbers[0]);
printf("Size of the array is %d\n", n);
printf("Here is the array before sorting:\n");
printArray(numbers, n);
sortArray(numbers, n);
printf("Here is the sorted array:\n");
printArray(numbers, n);
return 0;
}
in JavaScript
Here is the same program written in JavaScript:
function printArray(numbers) {
console.log(numbers.join(" "));
}
function sortArray(numbers) {
let n = numbers.length;
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
if (numbers[j] < numbers[i]) {
let temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
}
let numbers = [325, 135, 25, 1025, 68, 17, 512, 468];
console.log("Original array:");
printArray(numbers);
sortArray(numbers);
console.log("Sorted array:");
printArray(numbers);
in PHP
<?php
function printArray($numbers) {
echo implode(" ", $numbers) . "\n";
}
function sortArray(&$numbers) {
$n = count($numbers);
for ($i = 0; $i < $n - 1; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
if ($numbers[$j] < $numbers[$i]) {
$temp = $numbers[$i];
$numbers[$i] = $numbers[$j];
$numbers[$j] = $temp;
}
}
}
}
$numbers = [325, 135, 25, 1025, 68, 17, 512, 468];
echo "Original array:\n";
printArray($numbers);
sortArray($numbers);
echo "Sorted array:\n";
printArray($numbers);