-
Notifications
You must be signed in to change notification settings - Fork 32
/
sort.c
52 lines (41 loc) · 1.22 KB
/
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
46
47
48
49
50
51
52
#include <stdlib.h>
#include <stdio.h>
#define debug 0
// Comparison function for qsort()
int numcmp (const void *a, const void *b) {
int x = *((int*) a);
int y = *((int*) b);
if (x > y) return 1;
if (x < y) return -1;
return 0;
}
int main(int argc, char *argv[]) {
int i, length, *pt;
// Check for proper usage
if (argc < 2) {
fprintf(stderr, "%s: Aborting, not enough arguments.\n", argv[0]);
return (-1);
}
// Determine amount of numbers from argc
length = argc - 1;
#if debug
fprintf(stderr, "%s: DEBUG: %d numbers were passed.\n", argv[0], length);
#endif
// Allocate memory for array of number (and error check)
if ((pt = malloc(length * sizeof(int))) == NULL) {
fprintf(stderr, "%s: Could not allocate memory.\n", argv[0]);
}
// Read numbers into array
for (i = 0; i < length; i++) {
pt[i] = (int) strtol(argv[i+1], NULL, 10);
}
// Sort numbers
qsort(pt, length, sizeof(int), numcmp);
// Print out numbers
fprintf(stdout, "%s: Sorted output is: \n", argv[0]);
for (i=0; i<length; i++) {
fprintf(stdout, "%d ", pt[i]);
}
fprintf(stdout, "\n%s: FIN. \n", argv[0]);
return 0;
}