Add selection sort
This commit is contained in:
parent
abf965e7ce
commit
1f351ded8e
2 changed files with 35 additions and 4 deletions
31
selection-sort.c
Normal file
31
selection-sort.c
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
#include <stdio.h>
|
||||
|
||||
#define SWAP(x, y, T) do { T SWAP = x; x = y; y = SWAP; } while (0)
|
||||
|
||||
int index_of_min(int array[], int low, int high) {
|
||||
int result = low;
|
||||
for (int i = low; i <= high; i++) {
|
||||
if (array[i] < array[result])
|
||||
result = i;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void selection_sort(int array[], int high) {
|
||||
for (int i = 0; i <= high; i++) {
|
||||
int min = index_of_min(array, i, high);
|
||||
SWAP(array[i], array[min], int);
|
||||
}
|
||||
}
|
||||
|
||||
void print_array(int array[], int high) {
|
||||
for (int i = 0; i <= high; i++)
|
||||
printf("%d ", array[i]);
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
void main() {
|
||||
int array[] = {1, 3, 6, 2, 4, 73, 23, 61, 32, 64, 11, 32, 3, 2};
|
||||
selection_sort(array, 13);
|
||||
print_array(array, 13);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue