C++实训--快速排序

189 篇文章 3 订阅
180 篇文章 2 订阅
#include<iostream>
#include<algorithm>
using namespace std;

struct student 
{
    int sno;
    char name[20];

};
//qsort比较器
int com(const void *a, const void *b)//qsort基本比较器
{//void指针必须先进行强制类型转换
    return *((int *)a) - *((int *)b);

}
int com1(const void *a, const void *b)//student按照姓名排序
{
    return strcmp(((student *)a)->name ,((student *)b)->name);


}
//sort比较器
template<typename T>
bool compare(T &a, T &b)//sort基本比较器
{
    return a > b;
}

bool compare1(student &a, student &b)//student按照姓名排序
{
    return a.name>b.name;
}

void show(student a[], int num)//显示结构体
{
    int t=1;
    for (int i = 0; i < num; i++)
    {
        cout << a[i].sno << " " << a[i].name;
        cout << endl;
    }
}
void showarry(int a[], int num) {//显示数组
    for (int i = 0; i < 3; i++)
    {
        cout << a[i] << " ";
        
    }
}
int main() {

    int a[3] = { 2,4,1 };
    cout << "基本数组的排序:"<<endl;
    cout << "使用qsort排序结果:" << endl;
    qsort(a, 3, sizeof(int), com);
    showarry(a, 3);
    cout << endl;
    cout << "使用sort排序结果:" << endl;
    sort(a,a + 3, compare<int>);
    showarry(a, 3);
    cout << endl;

    cout <<"结构体排序:"<< endl;
    student s[3] = { {1,"jwt"},{2,"byj"}, {3,"abc"} };
    cout << "使用qsort排序结果:" << endl;
    qsort(s, 3, sizeof(student), com1);
    show(s, 3);
    cout << "使用sort排序结果:" << endl;  
    sort(s, s + 3, compare1);
    show(s, 3);
    system("pause");
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值