sort和qsort对字符数组排序

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;

//升序比较:第一个元素比第二个元素大返回正数(这是元素需要交换的条件)
int compare_rise(const void *a,const void *b) {
    return *(char*)a - *(char*)b;
}

//降序比较:第二个元素比第一个元素大返回正数(这是元素需要交换的条件)
int compare_fail(const void *a,const void *b) {
    return *(char*)b - *(char*)a ;
}

int cmp_sort(char a, char b) {
    return a > b;
}

void display( const char *array1, int len ) {
    for(int i = 0; i< len; ++i) {
             cout << array1[i] << " ";
    }
    cout << endl;
}

void qsort_char() {
    char str[] = "XELMNFUVWGYRSTZAHIJKBOPQCD";
    int len = strlen( str );
    cout << "原始数据:" << endl;
    display( str, len );
    cout << "升序排序后:" << endl;
    qsort(str, len, sizeof (*str), compare_rise); ///不必包含#include <algorithm>
    display( str, len );
    cout << "降序排序后:" << endl;
    qsort(str, len, sizeof (*str), compare_fail);
    display( str, len );
}

void sort_char() {
   char ch[100] = "XELMNFUVWGYRSTZAHIJKBOPQCD\n";
   int len = strlen(ch);
   //cout << "please input a string: " ;
  // cin >> ch;  ///scanf("%s", ch);or   gets(ch);
   cout << "升序排序后: ";
   sort(ch, ch+strlen(ch)); //必须包含#include <algorithm>
   display(ch, len);
   cout << "降序排序后: " << endl;
   sort(ch, ch+strlen(ch), cmp_sort);
   display(ch, len);
}

int main() {
    qsort_char();
    sort_char();
    return 0;
}

你可能感兴趣的:(sort和qsort对字符数组排序)