From 8eb6ef210c1b40e30035f1b5cd7395882abd194f Mon Sep 17 00:00:00 2001 From: Gabriele Bruno Franco Date: Sat, 10 Aug 2019 12:05:10 +0200 Subject: [PATCH 1/2] Add gnome sort --- sorting/gnome_sort.c | 46 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 sorting/gnome_sort.c diff --git a/sorting/gnome_sort.c b/sorting/gnome_sort.c new file mode 100644 index 00000000..ffd69d83 --- /dev/null +++ b/sorting/gnome_sort.c @@ -0,0 +1,46 @@ +#include +#include + +void sort(int *numbers, int size) +{ + int pos = 0; + while (pos < size) + { + if (numbers[pos] >= numbers[pos-1]) + pos++; + else + { + int tmp = numbers[pos-1]; + numbers[pos-1] = numbers[pos]; + numbers[pos] = tmp; + pos--; + + if (pos == 0) + pos = 1; + } + } +} + +void display(int *array, int n) +{ + for (int i = 0; i < n; ++i) + printf("%d ", array[i]); + printf("\n"); +} + +int main() +{ + int size = 6; + int *numbers = malloc(size*sizeof(int)); + printf("Insert %d unsorted numbers: \n", size); + for (int i = 0; i < size; ++i) + scanf("%d", &numbers[i]); + printf("Initial array: "); + display(numbers, size); + sort(numbers, size); + printf("Sorted array: "); + display(numbers, size); + free(numbers); + return 0; +} + From bbf8f1b991d55578a7e440b20da1411af22d3134 Mon Sep 17 00:00:00 2001 From: Gabriele Bruno Franco Date: Sat, 10 Aug 2019 13:19:05 +0200 Subject: [PATCH 2/2] Change for loop in gnome_sort.c, it's now C89-compatible --- sorting/gnome_sort.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sorting/gnome_sort.c b/sorting/gnome_sort.c index ffd69d83..3e67696e 100644 --- a/sorting/gnome_sort.c +++ b/sorting/gnome_sort.c @@ -31,9 +31,10 @@ void display(int *array, int n) int main() { int size = 6; + int i; int *numbers = malloc(size*sizeof(int)); printf("Insert %d unsorted numbers: \n", size); - for (int i = 0; i < size; ++i) + for (i = 0; i < size; ++i) scanf("%d", &numbers[i]); printf("Initial array: "); display(numbers, size);