c语言实现字符指针(字符串)数组的排序

需求:

"ff555d", "114ddd", "114dd","aaa", "aaab", "aaa" d对它们进行排序

头文件:

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

函数原型:

void printArray(char **buff,int len);

void sortBuff(char **buff[],int len);

实现方法:

void printArray(char **buff, int len){

    int i;

    for (i = 0; i < len; ++i){
        printf("%s
", buff[i]);
    }

}
 
 1 void sortBuff(char **buff,int len){
 2 
 3     char *temp;    //零时交换变量
 4 
 5     int i, j;
 6 
 7     /*选择排序法*/
 8     for (i = 0; i < len; ++i){
 9 
10         for (j = i + 1; j < len; ++j){
11 
12             if( strcmp(buff[i], buff[j]) > 0){ //应用string.h  
13                                                 //    int strcmp(    
14                 temp = buff[i];                    //        const char *string1,
15                                                 //        const char *string2 
16                 buff[i] = buff[j];                //    );
17                                                 //string1 > string2 返回值大于0 , == 为等于0, < 为小于0
18                 buff[j] = temp;                
19             
20 
21                 
22 
23             }
24 
25         }
26 
27     }
28 
29 }
View Code

测试:

 1 void main(){
 2 
 3     char *buff[] = {"ff555d", "114ddd", "114dd","aaa", "aaab", "aaa"};
 4 
 5     printf("排序前
");
 6 
 7     printArray(buff, sizeof(buff) / sizeof(buff[0]));
 8 
 9     printf("排序后
");
10 
11     sortBuff(buff, sizeof(buff) / sizeof(buff[0]));
12 
13     printArray(buff, sizeof(buff) / sizeof(buff[0]));
14 
15     system("pause");
16 }

运行结果:

原文地址:https://www.cnblogs.com/zhouquan-1992-04-06/p/6206188.html