Algorithms
Selection Sort
Selection sort repeatedly moves the smallest remaining value into the next output position.
Selection Sort
selection_sort.c
#include <stdio.h>
int main(void) {
int first = ;
int values[4] = {first, 1, 4, 2};
for (int i = 0; i < 3; i++) {
int minIndex = i;
for (int j = i + 1; j < 4; j++) {
if (values[j] < values[minIndex]) {
minIndex = j;
}
}
int temp = values[i];
values[i] = values[minIndex];
values[minIndex] = temp;
}
printf("first=%d last=%d\n", values[0], values[3]);
return 0;
}
#include <stdio.h>
int main(void) {
int first = ;
int values[4] = {first, 1, 4, 2};
for (int i = 0; i < 3; i++) {
int minIndex = i;
for (int j = i + 1; j < 4; j++) {
if (values[j] < values[minIndex]) {
minIndex = j;
}
}
int temp = values[i];
values[i] = values[minIndex];
values[minIndex] = temp;
}
printf("first=%d last=%d\n", values[0], values[3]);
return 0;
}
#include <stdio.h>
int main(void) {
int first = ;
int values[4] = {first, 1, 4, 2};
for (int i = 0; i < 3; i++) {
int minIndex = i;
for (int j = i + 1; j < 4; j++) {
if (values[j] < values[minIndex]) {
minIndex = j;
}
}
int temp = values[i];
values[i] = values[minIndex];
values[minIndex] = temp;
}
printf("first=%d last=%d\n", values[0], values[3]);
return 0;
}
minimum index
The inner loop tracks the position of the smallest remaining value.
swap
After the scan, a swap places that value into the current sorted position.