-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselection_sort.c
47 lines (40 loc) · 1.35 KB
/
selection_sort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*******************************************************************************
File: selection_sort.c
Author: CJ Dimaano
Date created: March 5, 2016
Last updated: April 5, 2016
Selection sort is a comparison-based sorting algorithm. It works by selecting
each element in an array and swapping it with the best element in the unsorted
portion of the array. The best element can only be determined by an exhaustive
search through the unsorted portion of the array.
*******************************************************************************/
#include "sort.h"
/**
* `selection_sort`
*
* Uses the selection sort algorithm to sort an array of integers.
*
* @param arr
* The array to be sorted.
*
* @param len
* The length of the array.
*/
void selection_sort(int * const arr, const size_t len) {
size_t i, j;
int best;
/*** Select each element in the array one at a time. ***/
for(i = 0; i < len - 1; i++) {
/*** Assume the current element is the best out of the remaining ***/
/*** unsorted elements. ***/
best = i;
/*** Search the remainder of the array for the best element. ***/
for(j = i + 1; j < len; j++) {
if(arr[best] > arr[j]) {
best = j;
}
}
/*** Swap the best element with the current element. ***/
swap(arr, i, best);
}
}