自学C——实现冒泡排序以及qsort的应用

一、qsort的应用 

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<assert.h>
#include<math.h>
#include<stdlib.h>
#include<search.h>
struct stu
{
    char name[20];
    int age;
};
int cmp_ss(const void* p1, const void* p2)
{
    return ((struct stu*)p1)->age - ((struct stu*)p2)->age;
}
int cmp_ss_name(const void* p1, const void* p2)
{
    return strcmp(((struct stu*)p1)->name, ((struct stu*)p2)->name);
}
int main()
{
    int arr[10] = { 9,8,7,6,5,4,3,2,1,0 };
    struct stu student[3] = { {"zhangsan",31},{"lisi",45},{"wanwu",47} };//数据结构的初始化。
    struct stu* p_stu = student;//数据结构指针
    int sz = sizeof(student) / sizeof(student[0]);
    //qsort(student, sz, sizeof(student[0]), cmp_ss);//根据年龄来排序
    qsort(student, sz, sizeof(student[0]), cmp_ss_name);//根据姓名首字母来排序
    int i = 0;
    for (i = 0; i < sz; i++)
    {
        printf("%d    %s\n", p_stu[i].age , p_stu[i].name);
    }
    return 0;

二、冒泡排序 

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<assert.h>
#include<math.h>
#include<stdlib.h>
#include<search.h>

void bubble_sort(int arr[], int sz)

{

        int i = 0;

        int j = 0;

        int t = 0;

        for (j = 0; j < sz - 1; j++)

        {

                for (i = 0; i < sz - 1 - j; i++)

                {

                        if (arr[i] > arr[i + 1])

                        {

                                t = arr[i];

                                arr[i] = arr[i + 1];

                                arr[i + 1] = t;

                        }

                }

        }

        for (i = 0; i < sz; i++)

        {

                printf("%d\n", arr[i]);

        }

}

int main()

{

        int arr[10] = { 9,8,7,6,5,4,3,2,1,0 };

        int sz = sizeof(arr) / sizeof(arr[0]);

        bubble_sort(arr,sz);

        return 0;

}

 

 三、运行的结果

1.qsort排序, 根据姓名首字母来排序

 

 2.qsort排序, 根据年龄来排序

 

3.冒泡排序 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值