qsort使用练习:练习使用库函数,qsort排序各种类型的数据
排序整型数据
# define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> /* qsort */ int int_cmp(const void* p1, const void* p2) { return (*(int*)p1 - *(int*)p2);//将void*类型转化为int*类型,并将其解引用 } int main() { int arr[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 }; int i = 0; qsort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(int), int_cmp);//(首元素地址,元素个数,字节数,比较函数) for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf("%d ", arr[i]); } printf("\n"); return 0; }
排序结构体
按照年龄比较
# define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> /* qsort */ struct Stu { char name[20]; int age; }; int cmp_by_age(const void* e1, const void* e2) { return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age; } void test() { struct Stu s[] = { {"zhangsan",20},{"lisi",19},{"wangwu",30} }; int sz = sizeof(s) / sizeof(s[0]); qsort(s, sz, sizeof(s[0]), cmp_by_age); } int main() { test(); return 0; }
按照姓名比较
# define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> /* qsort */ #include<string.h> struct Stu { char name[20]; int age; }; int cmp_by_name(const void* e1, const void* e2) { return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name); } void test() { struct Stu s[] = { {"zhangsan",20},{"lisi",19},{"wangwu",30}}; int sz = sizeof(s) / sizeof(s[0]); qsort(s, sz, sizeof(s[0]), cmp_by_name); } int main() { test(); return 0; }
qsort模拟实现:模仿qsort的功能实现一个通用的冒泡排序
# define _CRT_DEFINE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> /* qsort */ #include<string.h> int int_cmp(const void* p1, const void* p2) { return (*(int*)p1 - *(int*)p2); } void swap(void* p1, void* p2, int size) { int i = 0; for (i = 0; i < size; i++) { char tmp = *((char*)p1 + i); *((char*)p1 + i) = *((char*)p2 + i); *((char*)p2 + i) = tmp; } } void bubble(void* base, int count, int size, int(*cmp)(void*, void*)) { int i = 0; int j = 0; for (i = 0; i < count - 1; i++)//冒泡排序 { for (j = 0; j < count - i - 1; j++) { if (cmp((char*)base + j * size, (char*)base + (j + 1) * size) > 0) { swap((char*)base + j * size, (char*)base + (j + 1) * size, 4); } } } } int main() { int arr[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 }; int i = 0; bubble(arr, sizeof(arr) / sizeof(arr[0]), sizeof(int), int_cmp); for (i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf("%d ", arr[i]); } return 0; }