Skip to content

Instantly share code, notes, and snippets.

@blackknight36
Created February 26, 2017 22:04
Show Gist options
  • Save blackknight36/29e7e83a52ff1ecbcff2ca5728bd84e0 to your computer and use it in GitHub Desktop.
Save blackknight36/29e7e83a52ff1ecbcff2ca5728bd84e0 to your computer and use it in GitHub Desktop.
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
/*
* Array sorting code
*/
void gnomesort(long int n, long int ar[]) {
int i = 0;
while (i < n) {
if (i == 0 || ar[i-1] <= ar[i]) i++;
else {int tmp = ar[i]; ar[i] = ar[i-1]; ar[--i] = tmp;}
}
}
int main(){
int i = 0;
char *line = NULL;
size_t len = 0;
ssize_t read = 0;
read = getline(&line, &len, stdin);
char *p = line;
const char delim = ' ';
int count = read/sizeof(char);
long int numbers[count];
long int nb = 0;
int words = 0;
printf("count: %d bytes\n", count);
while (nb < count && *line) {
numbers[nb++] = strtol(p, &p, 10);
words++;
if (*p != delim ) {
break;
p++; /* skip, */
}
}
gnomesort(words, numbers);
printf("Sorted: ");
for ( int x = 0; x < words; x++ ) {
printf("%ld ", numbers[x]);
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment