用函数指针控制排序的顺序

// ptrsort.c -- 从键盘输入一系列字符串
// 将其按升序或降序排列 
// 然后,把排序后的字符串显示在屏幕上
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXLINES 25

int get_lines(char *lines[]);
void sort(char *p[], int n, int sort_type);
void print_strings(char *p[], int n);
int alpha(char *p1, char *p2);
int reverse(char *p1, char *p2);

char *lines[MAXLINES]; 

int main(void){
    int number_of_lines, sort_type;
    
    //从键盘读入多行字符串
    number_of_lines = get_lines(lines); 
    if(number_of_lines < 0){
        puts("Memory allocation error");
        exit(-1);
    }
    puts("Enter 0 for reverse order sort, 1 for alphabetical: ");
    scanf("%d", &sort_type);
    sort(lines, number_of_lines, sort_type);
    printf("\n");
    print_strings(lines, number_of_lines);
    return 0;
}

int get_lines(char *lines[]){
    int n = 0;
    char buffer[80];  // 临时储存每一行字符串
    puts("Enter one lines at time; enter a blank when done.");
    
    while(n < MAXLINES && gets(buffer) != 0 && buffer[0] != '\0'){
        if((lines[n] = (char *)malloc(strlen(buffer) + 1)) == NULL)
            return -1;
        strcpy(lines[n++], buffer);
    }
    return n;
} // get_lines结束 

void sort(char *p[], int n, int sort_type){
    int a, b;
    char *x;
    
    //函数指针
    int (*compare)(char *s1, char *s2);
    
    // 根据sort_type参数的值,让指针指向相应的比较函数 
    compare = (sort_type) ? reverse : alpha;
//    if(0 == sort_type){
//        compare = reverse;
//    }
//    if(1 == sort_type){
//        compare = alpha;
//    }
    
    for(a = 1; a < n; a++){
        for(b = 0; b < n-1; b++){
            if(compare(p[b], p[b+1]) > 0){
                x = p[b];
                p[b] = p[b+1];
                p[b+1] = x;
            }
        }
    } 
}  // sort结束 

void print_strings(char *p[], int n){
    int count;
    for(count = 0; count < n; count++){
        printf("%s\n", p[count]);
    }
}

int alpha(char *p1, char *p2){ // 按字母顺序比较
    return (strcmp(p2, p1)); 
}

int reverse(char *p1, char *p2){ //按反向字母比较
    return (strcmp(p1, p2)); 
}


转载于:https://my.oschina.net/u/241930/blog/523819

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值