-
Notifications
You must be signed in to change notification settings - Fork 0
/
sel_sort.c
49 lines (40 loc) · 1.08 KB
/
sel_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
48
49
/* vim:ts=4:sw=4:et:so=10:ls=2:
* Vim modeline for consistent editor settings across files.
*
* sel_sort.c
* A brief description of the file.
*
* Description:
* Selection sort based on the example from The Algorithm Design Manual
*
*/
#include <stdio.h>
void swap(char *, char *);
static void selection_sort(char s[], int n) {
int i, j; // counters
int min = 0; // hold the index of the smallest found value
// Identify the smallest remaining element in the unsorted
// portion of the set and place it at the end of the sorted
// portion.
for (i = 0; i < n; i++) {
for (j = i, min = i; j < n; j++) {
if (s[j] < s[min]) {
min = j;
// min now is the index
// of the smallest value
}
}
swap(&s[i], &s[min]);
}
}
int main(void) {
char s[] = "INSERTION";
selection_sort(s, 9);
printf("%s\n", s);
return 0;
}
void swap(char *x, char *y) {
char temp = *y;
*y = *x;
*x = temp;
}