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\n", 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("排序前\n");
 6 
 7     printArray(buff, sizeof(buff) / sizeof(buff[0]));
 8 
 9     printf("排序后\n");
10 
11     sortBuff(buff, sizeof(buff) / sizeof(buff[0]));
12 
13     printArray(buff, sizeof(buff) / sizeof(buff[0]));
14 
15     system("pause");
16 }

運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM