Sorting a list of Strings in Alphabetical order (C)

眉间皱痕 提交于 2019-12-01 01:57:22

Sorting an array of strings are real simple. Just use qsort and the existing compare function (i.e. strcmp)

Example:

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

#define NAMES 5
#define NAME_LEN 10

void print_names(char names[][10])
{
    int i;
    for(i=0; i<NAMES; ++i)
    {
        printf("%s\n", names[i]);
    }
}

int main(void) {
    char names[NAMES][NAME_LEN] = { "xxx", "uuu", "ccc", "aaa", "bbb" };

    print_names(names);
    printf("---------------------------------\n");

    qsort(names, NAMES, NAME_LEN, strcmp);

    print_names(names);

    return 0;
}

You can use bubble sort algorithm as well!

#include <stdio.h>
#include <string.h>

int main(void) {
    char *names[] = { "xxx", "uuu", "ccc", "aaa", "bbb" };
    char *tmp;
    int i = 0, j;
    for(i; names[i]; i++) {
        for(j = 0; names[j]; j++) {
            if(strcmp(names[i], names[j]) < 0) {
                tmp = names[i];
                names[i] = names[j];
                names[j] = tmp;
            }
        }
    }
    for(i = 0; names[i]; i++) printf("%s\n", names[i]);
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!