一、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.冒泡排序