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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
/* malloc version */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINES 5000
char *lineptr[MAXLINES];
int readlines(char *lineptr[], int max);
void writelines(char *lineptr[], int max);
void my_qsort(char *lineptr[], int left, int right);
int
main(void)
{
int nlines;
if ((nlines = readlines(lineptr, MAXLINES)) > 0) {
my_qsort(lineptr, 0, nlines);
writelines(lineptr, nlines);
return 0;
} else {
printf("Err: lines, lines everywhere\n"); /* too much lines / input too big */
return 1;
}
return 0;
}
#define MAXLEN 1000
int sneed_getline(char str[], int max);
int
readlines(char *lineptr[], int max)
{
int len, nlines;
char* temp, line[MAXLEN];
for (nlines = 0; (len = sneed_getline(line, MAXLEN)) > 0; nlines++) {
if (nlines < max && (temp = malloc(len+1)) != NULL) {
strcpy(temp, line);
lineptr[nlines] = temp;
}
else
return -1;
}
return nlines;
}
void
writelines(char *lineptr[], int max)
{
while (max--)
printf("%s\n", *lineptr++);
}
int
sneed_getline(char str[], int max)
{
char input;
char *str_og;
str_og = str;
--max;
while (--max && (input = getchar()) != EOF && input != '\n')
*str++ = input;
/*
if (input == '\n' && max)
*str++ = input; */
*str = '\0';
return str - str_og;
}
void swap(char *lineptr[], int to, int from);
void
my_qsort(char *lineptr[], int left, int right)
{
int i, last;
if (left >= right)
return;
swap (lineptr, left, (left+right)/2);
last = left;
for (i = left+1; i < right; i++)
if (strcmp(lineptr[i], lineptr[left]) < 0)
swap(lineptr, i, ++last);
swap(lineptr, left, last);
my_qsort(lineptr, left, last - 1);
my_qsort(lineptr, last + 1, right);
}
void
swap(char *lineptr[], int to, int from)
{
char *temp;
temp = lineptr[to];
lineptr[to] = lineptr[from];
lineptr[from] = temp;
}
|