Skip to content

Commit

Permalink
Merge pull request TheAlgorithms#251 from gbrunofranco/gnome_sort
Browse files Browse the repository at this point in the history
Add gnome sort
  • Loading branch information
StepfenShawn authored Aug 10, 2019
2 parents e99bebc + bbf8f1b commit 823058f
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions sorting/gnome_sort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#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)
{
for (int 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;
}

0 comments on commit 823058f

Please sign in to comment.