- #include <iostream>
- #include <cstdlib>
- #include <cstring>
- #include <algorithm>
- using namespace std;
- //qsort()返回值必须是int,两个参数的类型必须都是const void *,sort()头文件#include<algorithm>,qsort头文件#include<cstdlib>
- //升序比较:第一个元素比第二个元素大返回正数(这是元素需要交换的条件)
- 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对字符数组排序
最新推荐文章于 2023-05-16 21:14:59 发布