Sitzung: Jeden Freitag ab 14:30 s.t. online. Falls ihr den Link haben wollt, schreibt uns.

C-Kurs/StringArraySortieren/Musterlösung

#include <stdio.h>
#include <stdlib.h>

void mem_copy(char *dest, char *src, int len) {
    int i;
    for (i=0; i<len; i++) {
        *dest++ = *src++;
    }
}

int str_compare(char *a, char *b) {
    int diff;
    
    do {
        char ca = *a++;
        char cb = *b++;

        if ((ca == '\0') && (cb = '\0'))
            return 0;

        diff = ca-cb;
    } while (diff == 0);
    
    return diff;
}

void sort(char **list, int length) {
    int i, j;
    for (i=0; i<length-1; i++) {
        for (j=0; j<length-i-1; j++) {
            if (str_compare(list[j], list[j+1]) > 0) {
                char *tmp = list[j];
                list[j] = list[j+1];
                list[j+1] = tmp;
            }
        }
    }
}

int main(int argc, char *argv[]) {
    char **list = malloc(argc * sizeof(char *));
    mem_copy((char*)list, (char*)argv, argc * sizeof(char *));
    sort(list, argc);
    
    int i;
    for (i=0; i<argc; i++) {
        printf("%02d: %s\n", (i+1), list[i]);
    }
    
    return 0;
}