5 #define MAXLINES 5000 // max number of lines sorted
6 #define MAXLEN 1000 // maximum length of each line
7 #define ALLOCSIZE 10000 // size of available space
9 int readlines(char *lineprt
[], int nlines
);
10 void writelines(char *lineprt
[], int nlines
);
11 void new_qsort(void *lineptr
[], int left
, int right
, int (*comp
)(void *, void*));
12 int numcmp(char *, char *);
13 void swap(void *v
[], int i
, int j
);
14 int getline(char s
[], int lim
);
17 char *lineptr
[MAXLINES
]; // pointers to next lines
18 static char allocbuf
[ALLOCSIZE
];
19 static char *allocp
= allocbuf
;
23 Get chars ony by one from stdin. Load them into array of chars within lim.
26 int getline(char s
[], int lim
)
30 while(--lim
> 0 && (c
= getchar()) != EOF
&& c
!= '\n')
38 void new_qsort(void *v
[], int left
, int right
, int (*comp
)(void *, void*))
41 void swap(void *v
[], int, int);
45 swap(v
, left
, (left
+ right
)/2);
47 for(i
= left
+1; i
<= right
; i
++)
48 if((*comp
)(v
[i
], v
[left
]) < 0)
51 new_qsort(v
, left
, last
-1, comp
);
52 new_qsort(v
, last
+1, right
, comp
);
55 void swap(void *v
[], int i
, int j
)
65 Compare two strings numerically.
68 int numcmp(char *s1
, char *s2
)
85 Use getline to obtain data from stdin.
87 Put data into array of pointers to char, as long as number of lines less than maxlines.
90 int readlines(char *lineprt
[], int maxlines
)
93 char *p
, line
[MAXLEN
];
96 while((len
= getline(line
, MAXLEN
)) > 0)
98 if(nlines
>= maxlines
|| (p
= alloc(len
)) == NULL
)
102 line
[len
-1] = '\0'; // delete newline
104 lineptr
[nlines
++] = p
;
111 write ouput lines to stdout
113 input is an array of pointers to char and the number of lines stored
118 void writelines(char *lineptr
[], int nlines
)
121 printf("%s\n", *lineptr
++);
126 if(allocbuf
+ ALLOCSIZE
- allocp
>= n
)
129 return allocp
-n
; // old pointer
137 Sort lines in input numerically.
139 If -n switch entered, sort lines numerically.
141 Program is limited by buffers of both maximum number of lines and maximum length of lines.
145 int main(int argc
, char *argv
[])
150 if(argc
> 1 && strcmp(argv
[1], "-n") == 0)
152 if((nlines
= readlines(lineptr
, MAXLINES
)) >= 0)
154 new_qsort((void **) lineptr
, 0, nlines
-1, (int(*)(void *,void *))(numeric
? numcmp
: strcmp
));
155 writelines(lineptr
, nlines
);
158 printf("Input: Too many lines to sort\n");