98 lines
2.3 KiB
C
98 lines
2.3 KiB
C
// vim: set ts=4 sw=4 et tw=80:
|
|
#include <stdio.h>
|
|
#include <ctype.h>
|
|
#include <unistd.h>
|
|
#include <string.h>
|
|
#include <stdbool.h>
|
|
#define MAX_LINE_SIZE 1001
|
|
#define DEBUG
|
|
|
|
void swap(char** a, char** b);
|
|
void print_words(char* words[], size_t start, size_t end);
|
|
void quicksort_string(char* strings[static 1], size_t start, size_t end);
|
|
|
|
void swap(char** a, char** b) {
|
|
char* tmp;
|
|
tmp = *a;
|
|
*a = *b;
|
|
*b = tmp;
|
|
}
|
|
|
|
void quicksort_string(char* strings[static 1], size_t start, size_t end) {
|
|
|
|
#ifdef DEBUG
|
|
sleep(1);
|
|
printf("%ld - %ld: ", start, end);
|
|
print_words(strings, start, end);
|
|
putchar('\n');
|
|
#endif
|
|
|
|
if (end - start < 2) {
|
|
#ifdef DEBUG
|
|
puts("returning");
|
|
#endif
|
|
return;
|
|
}
|
|
|
|
char* pivot = strings[end - 1];
|
|
size_t i, gt = end - 1;
|
|
for (i = start; i < gt; i++) {
|
|
#ifdef DEBUG
|
|
printf("i=%ld gt=%ld\n", i, gt);
|
|
print_words(strings, start, end);
|
|
putchar('\n');
|
|
#endif
|
|
if (strcmp(strings[i], pivot) > 0) {
|
|
swap(&strings[--gt], &strings[i--]);
|
|
}
|
|
}
|
|
swap(&strings[gt], &strings[end - 1]);
|
|
|
|
#ifdef DEBUG
|
|
print_words(strings, start, gt);
|
|
printf("| %s | ", strings[gt]);
|
|
print_words(strings, gt + 1, end);
|
|
putchar('\n');
|
|
#endif
|
|
|
|
quicksort_string(strings, start, gt);
|
|
quicksort_string(strings, gt + 1, end);
|
|
}
|
|
|
|
void print_words(char* words[], size_t start, size_t end) {
|
|
size_t i;
|
|
for (i = start; i < end; i++) {
|
|
printf("%s ", words[i] == NULL ? "NULL" : words[i]);
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
char line[MAX_LINE_SIZE];
|
|
char* words[MAX_LINE_SIZE / 2];
|
|
char* word = line;
|
|
size_t chars = 0, words_len = 0;
|
|
int c;
|
|
bool last_alpha = false;
|
|
while ((c = getchar()) != EOF) {
|
|
if (!isalpha(c) || c == '\n') {
|
|
if (last_alpha) {
|
|
line[chars++] = '\0';
|
|
words[words_len++] = word;
|
|
word = line + chars;
|
|
last_alpha = false;
|
|
}
|
|
if (c == '\n') {
|
|
quicksort_string(words, 0, words_len);
|
|
print_words(words, 0, words_len);
|
|
putchar('\n');
|
|
chars = 0;
|
|
words_len = 0;
|
|
word = line;
|
|
}
|
|
} else {
|
|
line[chars++] = c;
|
|
last_alpha = true;
|
|
}
|
|
}
|
|
}
|
|
|