kindwolf.org Git repositories sorting-algorithms / master selection-sort.c
master

Tree @master (Download .tar.gz)

selection-sort.c @masterraw · history · blame

/**
 * Copyright © 2016-2019 Xavier G. <xavier@kindwolf.org>
 * 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.
 */

void array_sort(unsigned int **array, unsigned int count);
#define ARRAY_SORT 1
#include "common.c"

/*
 * 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) */
	}
}