Add selection sort
This commit is contained in:
parent
abf965e7ce
commit
1f351ded8e
2 changed files with 35 additions and 4 deletions
|
|
@ -2,9 +2,9 @@
|
||||||
|
|
||||||
#define SWAP(x, y, T) do { T SWAP = x; x = y; y = SWAP; } while (0)
|
#define SWAP(x, y, T) do { T SWAP = x; x = y; y = SWAP; } while (0)
|
||||||
|
|
||||||
void gnome_sort(int array[], int n) {
|
void gnome_sort(int array[], int high) {
|
||||||
int i = 0;
|
int i = 0;
|
||||||
while (i < n) {
|
while (i < high) {
|
||||||
if (array[i] > array[i+1]) {
|
if (array[i] > array[i+1]) {
|
||||||
SWAP(array[i], array[i+1], int);
|
SWAP(array[i], array[i+1], int);
|
||||||
if (i > 0) i--;
|
if (i > 0) i--;
|
||||||
|
|
@ -13,8 +13,8 @@ void gnome_sort(int array[], int n) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void print_array(int array[], int n) {
|
void print_array(int array[], int high) {
|
||||||
for (int i = 0; i < n; i++)
|
for (int i = 0; i <= high; i++)
|
||||||
printf("%d ", array[i]);
|
printf("%d ", array[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
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