-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathgnome_sort.c
45 lines (41 loc) · 911 Bytes
/
gnome_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
#include <stdio.h>
#include <stdlib.h>
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)
{
int i;
for (i = 0; i < n; ++i) printf("%d ", array[i]);
printf("\n");
}
int main()
{
int size = 6;
int i;
int *numbers = malloc(size * sizeof(int));
printf("Insert %d unsorted numbers: \n", size);
for (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;
}