/* * Program to test/demo sorting using "random" data. * * Requires two command-line arguments, count and seed. * * Incomplete -- doesn't actually sort data yet. */ #include #include void sort(int sz, int data[]); int main(int argc, char *argv[]) { if (argc < 3) { puts("requires two command-line arguments, count and seed"); return 1; } char *endptr; long count = strtol(argv[1], &endptr, 10); if ((*endptr != '\0') || (count <= 0)) { puts("count must be positive integer"); return 1; } long seed = strtol(argv[2], &endptr, 10); if ((*endptr != '\0') || (count <= 0)) { puts("seed must be positive integer"); return 1; } int * data = malloc(sizeof(data[0]) * count); if (data == NULL) { printf("cannot allocate array of size %ld\n", count); return 1; } /* fill array with "random" values */ srand(seed); for (int i = 0; i < count; ++i) { data[i] = rand(); } /* sort array */ sort(count, data); /* FIXME */ /* print result */ for (int i = 0; i < count; ++i) { printf("element %d is %d\n", i, data[i]); } /* check "is it sorted" */ puts(""); for (int i = 0; i < count-1; ++i) { if (data[i] > data[i+1]) { printf("element %d out of order\n", i+1); } } free(data); return 0; } int compare(const void *e1, const void *e2) { int *i1 = (int *) e1; int *i2 = (int *) e2; if (*i1 < *i2) return -1; else if (*i1 > *i2) return 1; else return 0; } void sort(int sz, int data[]) { qsort(data, sz, sizeof data[0], compare); }