-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselection_sort.c
50 lines (39 loc) · 1.12 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
48
49
50
#include <stdio.h>
#include <stddef.h>
void xor_swap(int *x, int *y) {
if (*x == *y)
return;
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
void selection_sort(int *arr, size_t size) {
size_t min_idx;
for (size_t i = 0; i < size; i++) {
min_idx = i;
for (size_t j = i + 1; j < size; j++) {
if (arr[j] < arr[min_idx])
min_idx = j;
}
if (min_idx != i)
xor_swap(&arr[min_idx], &arr[i]);
}
}
int main(void) {
int arr[] = { 5, 2, 8, 1, 4 };
int expected[] = { 1, 2, 4, 5, 8 };
size_t size = sizeof(arr) / sizeof(arr[0]);
printf("Testing Selection Sort:\n");
selection_sort(arr, size);
printf("Expected: ");
for (size_t i = 0; i < size; i++) {
printf("%d ", expected[i]);
}
printf("\n");
printf("Actual: ");
for (size_t i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}