当前位置:网站首页>C language -- the use and Simulation of library function qsort
C language -- the use and Simulation of library function qsort
2022-07-21 19:01:00 【Knock the code, Liuchuan maple】
author : Knock on the code の Rukawa Kaede
Blog home page : Liuchuan Feng's blog
special column :C Language from entry to advanced
Quotations :Stay hungry stay foolish
If a worker wants to do a good job, he must sharpen his tools first , I'd like to introduce you to a super cow harvest factory offer tool —— Cattle from
List of articles
2.qsort Realize sorting of different types of data
3.qsort Simulation Implementation of
1.qsort Function introduction
Function definition :
Function parameter :
void* base
The starting position of the data to be sorted
size_t num
The number of data elements to be sorted
size_t width
The size of the data elements to be sorted , In bytes
int (*compar)(const void*,const void*)
Is a function pointer , The function function is to compare
Because the type of data to be sorted by the sorting algorithm is different , The comparison method is also different , Therefore, it is necessary to provide users with a customized comparison function
2.qsort Realize sorting of different types of data
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> int cmp_int(const void* e1, const void* e2) { return (*(int*)e1 - *(int*)e2); } void test1() { int arr[] = {9,8,7,6,5,4,3,2,1,0}; int sz = sizeof(arr) / sizeof(arr[0]); qsort(arr, sz, sizeof(arr[0]), cmp_int); int i = 0; for (i = 0; i < sz; i++) { printf("%d ", arr[i]); } } struct Stu { char name[20]; int age; }; int cmp_stu_by_name(const void* e1, const* e2) { return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name); } void test2() { struct Stu s[] = { {"zhangsan",20},{"lisi",21},"wangwu",19}; int sz = sizeof(s) / sizeof(s[0]); qsort(s, sz, sizeof(s[0]), cmp_stu_by_name); int i = 0; for (i = 0; i < 3; i++) { printf("%s %d ", s[i].name, s[i].age); } } int main() { test1(); prinf("\n"); test2(); return 0; }
test1 and test2 Two functions for each int Sort type data and structure type data , here void* It is worth mentioning
void* The function of the pointer :
int main() { int a = 10; char* pa = &a; return 0; }
As the warning says , Their types are incompatible , But if use void* Define a pointer variable to receive int* The data will not have warnings , This explanation void* A pointer is a pointer without a specific type , Can accept any type of address , Is generic , Just because it has no specific type , It cannot be dereferenced , You can't add or subtract , Want to dereference it , You only need to cast the address ,qsort Function parameters of use void* Type is also because I don't know the address of what type of data the user will send , use void* Can receive any type of address , Improved qsort Utility of function
3.qsort Simulation Implementation of
analysis :
Reference resources qsort We know the parameters of the function : When designing functions, we don't know what type of data the user wants to transmit , So we will use the void* Type pointer to record the starting position of sorting data , Finally, a comparison function provided will also be used void*; Know the number and width of elements , You can find these data one by one
As shown in the figure above , base Cast to char* Type pointer can access one byte at a time , If it is converted to int * Skip the next time 4 A byte is too much , Convert to char* Posterior Union width It is equivalent to comparing by adding the offset to the starting position , Pass after comparison Swap Function , To achieve the purpose of sorting
Simulation Implementation :
// In exchange for void Swap(char* buf1, char* buf2, int width) { int i = 0; for (i = 0; i < width; i++) { char tmp = *buf1; *buf1 = *buf2; *buf2 = tmp; buf1++; buf2++; } } void bubble_sort(void* base, int sz, int width, int(*cmp)(const void* e1, const void* e2)) { int i = 0; for (i = 0; i < sz - 1; i++) { // A sequence int flag = 1; int j = 0; for (j = 0; j < sz - 1; j++) { if (cmp((char*)base + j * width, (char*)base + (j + 1) * width)>0) { Swap((char*)base + j * width, (char*)base + (j + 1) * width,width); flag = 0; } } if (flag == 1) break; } }
int cmp_int(const void* e1, const void* e2) { return (*(int*)e1 - *(int*)e2); } void test1() { int arr[] = { 9,8,7,6,5,4,3,2,1,0 }; int sz = sizeof(arr) / sizeof(arr[0]); qsort(arr, sz, sizeof(arr[0]), cmp_int); int i = 0; for (i = 0; i < sz; i++) { printf("%d ", arr[i]); } } struct Stu { char name[20]; int age; }; int cmp_stu_by_name(const void* e1, const* e2) { return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name); } void test2() { struct Stu s[] = { {"zhangsan",20},{"lisi",21},"wangwu",19}; int sz = sizeof(s) / sizeof(s[0]); bubble_sort(s, sz, sizeof(s[0]), cmp_stu_by_name); int i = 0; for (i = 0; i < 3; i++) { printf("%s %d ", s[i].name, s[i].age); } } int main() { test1(); printf("\n"); test2(); return 0; }
“ This is the sharing of this issue , Remember to give the blogger a three-year run , Your support is the biggest driving force of my creation !”
边栏推荐
- 苹果公司发布watchOS 8.7 包含错误修复和安全更新
- If the recommendation effect is not satisfactory, it's better to try to learn the propeller chart
- w10系统,怎样调整应用的分辨率
- TCP协议
- 手工遍历二叉树的技巧
- canal.deployer-1.1.6 遇到dump address has an error, retrying. caused by问题
- QT4、5、6各版本之间的特点和选择
- The problem of removing spaces at the beginning and end of strings
- [04] through the power consumption wall, what aspects should we improve "performance"?
- Protocole TCP
猜你喜欢
若依框架之swagger接口文档
Exchange class sorting
Zhongang Mining: four trends of fluorite industry development
手工遍历二叉树的技巧
Flyter icons built-in icon library materialicons Encyclopedia
Oracle startup command
canal.deployer-1.1.6 遇到dump address has an error, retrying. caused by问题
用VIM正则表达式进行批量替换的小练习
Small exercise of batch replacement with VIM regular expression
Redis+Caffeine两级缓存,让访问速度纵享丝滑
随机推荐
ACM training July 4
TCP协议
电子招标采购商城系统:优化传统采购业务,提速企业数字化升级
Leetcode - prefix sum and difference
canal.deployer-1.1.6 遇到dump address has an error, retrying. caused by问题
[translation] improve stability and reliability with kubernetes + helm + flux!
synchronized锁范围
JWT(JSON Web Token) 认证 :目前最流行的跨域认证解决方案
The new red envelope cover platform can build the source code of the independent background of the sub station
Protocole TCP
Description du développement de l'ESB en combinaison avec la plateforme UMC Cloud
Pytorch uses nn Unfold realizes convolution operation again
Next generation wireless LAN -- PHY interoperability between 802.11n and traditional 11ag OFDM devices
Solution to field 'ID' doesn't have a default value error
Oracle export table data -dmp file
求解单源最短路径的手工实现
rk3128扬声器spk 和耳机hp声音大小调试
El table supports paging multiple selection
STM32F40x 最小系统
Embedded learning: introduction to Cortex-M series chips