Lesson 16 of 23

sort

The sort Command

sort reads lines and prints them in alphabetical order:

$ printf "banana\napple\ncherry\n" | sort
apple
banana
cherry

Your Implementation

Write void my_sort(const char *s) that prints lines in sorted order.

The approach: first collect every line into a 2D array, then sort that array with bubble sort, then print.

void my_sort(const char *s) {
    char lines[64][256];
    int count = 0;

    // Collect lines
    while (*s) {
        char *out = lines[count];
        while (*s && *s != '\n') { *out++ = *s++; }
        *out = '\0';
        if (*s == '\n') s++;
        count++;
    }

    // Bubble sort
    for (int i = 0; i < count - 1; i++) {
        for (int j = 0; j < count - 1 - i; j++) {
            const char *a = lines[j], *b = lines[j + 1];
            while (*a && *a == *b) { a++; b++; }
            if (*a > *b) {
                char tmp[256];
                // swap lines[j] and lines[j+1]
                ...
            }
        }
    }

    for (int i = 0; i < count; i++) printf("%s\n", lines[i]);
}

Bubble Sort

Bubble sort repeatedly walks adjacent pairs and swaps them if out of order. After each pass the largest unsorted element "bubbles" to its final position.

Comparing strings without strcmp: walk both pointers together while characters match, then compare the diverging characters. If *a > *b, line a sorts after line b.

Swapping strings without strcpy: copy into a temporary buffer, then overwrite each direction. Since each line is stored as a fixed-size char[256], swapping means copying the bytes of one into tmp, copying the other into the first, then copying tmp into the second.

Your Task

Implement my_sort that prints lines in ascending alphabetical order.

TCC compiler loading...
Loading...
Click "Run" to execute your code.