-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort.c
More file actions
82 lines (67 loc) · 1.77 KB
/
sort.c
File metadata and controls
82 lines (67 loc) · 1.77 KB
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
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFFER_SIZE 65536
#define MAX_LINES 10000
static char buffer[BUFFER_SIZE];
static char *lines[MAX_LINES];
static int compare_strings(const char *a, const char *b) {
while (*a && *b && *a == *b) {
a++;
b++;
}
return *a - *b;
}
static void quicksort(char **arr, int low, int high) {
if (low < high) {
char *pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (compare_strings(arr[j], pivot) < 0) {
i++;
char *temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
char *temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
int pi = i + 1;
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
}
int main(int argc, char **argv) {
int fd, line_count = 0;
ssize_t bytes_read;
char *p, *line_start;
if (argc > 1) {
fd = open(argv[1], O_RDONLY);
if (fd == -1) return 1;
} else {
fd = 0;
}
bytes_read = read(fd, buffer, BUFFER_SIZE);
if (bytes_read <= 0) {
if (fd != 0) close(fd);
return 0;
}
line_start = buffer;
p = buffer;
while (p < buffer + bytes_read && line_count < MAX_LINES) {
if (*p == '\n') {
*p = '\0';
lines[line_count++] = line_start;
line_start = p + 1;
}
p++;
}
quicksort(lines, 0, line_count - 1);
for (int i = 0; i < line_count; i++) {
write(1, lines[i], __builtin_strlen(lines[i]));
write(1, "\n", 1);
}
if (fd != 0) close(fd);
return 0;
}