易百教程

使用冒泡排序对数组字符串进行排序

使用strcmp()函数比较字符串以确定是否需要交换它们。

示例代码

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

int main()
{
    char *fruit[] = {
        "watermelon",
        "banana",
        "pear",
        "apple",
        "coconut",
        "grape",
        "blueberry"
    };
    char *temp;
    int a,b,x;

    for(a=0;a<6;a++)
        for(b=a+1;b<7;b++)
            if(strcmp(*(fruit+a),*(fruit+b)) > 0 )
            {
                temp = *(fruit+a);
                *(fruit+a) = *(fruit+b);
                *(fruit+b) = temp;
            }

    for(x=0;x<7;x++)
        puts(fruit[x]);

    return(0);
}

执行上面示例代码,得到以下结果:

apple
banana
blueberry
coconut
grape
pear
watermelon