TheAlgorithms-C/sorting/gnome_sort.c

49 lines
921 B
C
Raw Normal View History

2019-08-10 18:05:10 +08:00
#include <stdio.h>
#include <stdlib.h>
void sort(int *numbers, int size)
{
int pos = 0;
while (pos < size)
{
2020-02-02 16:15:59 +08:00
if (pos == 0)
pos = 1;
2020-04-19 09:14:49 +08:00
if (numbers[pos] >= numbers[pos-1] || pos == 0)
2019-08-10 18:05:10 +08:00
pos++;
2020-02-02 16:15:59 +08:00
else
2019-08-10 18:05:10 +08:00
{
int tmp = numbers[pos-1];
numbers[pos-1] = numbers[pos];
numbers[pos] = tmp;
pos--;
2020-02-02 16:15:59 +08:00
2019-08-10 18:05:10 +08:00
}
}
}
void display(int *array, int n)
{
int i;
for (i = 0; i < n; ++i)
2019-08-10 18:05:10 +08:00
printf("%d ", array[i]);
printf("\n");
}
int main()
{
int size = 6;
int i;
2019-08-10 18:05:10 +08:00
int *numbers = malloc(size*sizeof(int));
printf("Insert %d unsorted numbers: \n", size);
for (i = 0; i < size; ++i)
2019-08-10 18:05:10 +08:00
scanf("%d", &numbers[i]);
printf("Initial array: ");
display(numbers, size);
sort(numbers, size);
printf("Sorted array: ");
display(numbers, size);
free(numbers);
return 0;
}