selection-sort.c
 44632a76 ``` /** ``` 64863b26 ``` * Copyright © 2016-2019 Xavier G. ``` 44632a76 ``` * This work is free. You can redistribute it and/or modify it under the * terms of the Do What The Fuck You Want To Public License, Version 2, * as published by Sam Hocevar. See the COPYING file for more details. */ ``` 0fc9a6f7 ``` void array_sort(unsigned int **array, unsigned int count); #define ARRAY_SORT 1 #include "common.c" ``` 44632a76 ``` /* * Implementation of selection sort: */ void array_sort(unsigned int **array, unsigned int count) { unsigned int *src; /* Unsorted, source array. */ unsigned int i, j; /* Indices. */ unsigned int smallest_value; /* Smallest value in the unsorted sublist. */ unsigned int smallest_index; /* Index of the smallest value in the unsorted sublist. */ /* Do nothing unless there are at least two items to sort: */ if (count < 2) return; /* Selection-sort is an in-place algorithm, i.e. we work directly on the provided array: */ src = *array; for (i = 0; i < count - 1; ++ i) { /* Find the smallest element in the unsorted sublist: */ smallest_value = src[i]; smallest_index = i; for (j = i + 1; j < count; ++ j) { if (src[j] < smallest_value) { smallest_value = src[j]; smallest_index = j; } } /* Exchange it with the leftmost unsorted element: */ if (smallest_index != i) { src[smallest_index] = src[i]; src[i] = smallest_value; } /* Move the sublist boundaries one element to the right: */ /* (this is done by "++ i" in the for loop) */ } } ```