Simulate the realization of qsort library functions
First look at the qsort data prototype
void qsort( void * base ,//The starting position of the data to be sorted
size_t num ,//Number of elements sorted
size_t width , sorted element width
int ( * cmp )(const void * e1 , const void * e2 ) );//Function pointer-comparison function of the two elements to be compared
Here is the usage of the qsort library function:
#include <stdio.h>
#include <stdlib.h>
void print_arr(int* arr, int sz)
{
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int cmp_int(const void* e1, const void* e2)
{
return *(int*)e1 - *(int*)e2;
}
int main()
{
int arr[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
int sz = sizeof(arr) / sizeof(arr[0]);
qsort(arr, sz, sizeof(arr[0]), cmp_int);
print_arr(arr, sz);
return 0;
}
Here is the realization of the qsort library function with bubble sort simulation:
#include <stdio.h>
#include <stdlib.h>
void _swap(char* buf1, char* buf2, int width)
{
int i = 0;
for (i = 0; i < width; i++)
{
int tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
bubble_sort(void* base, size_t sz, size_t width, int(*cmp)(const void* e1, const void* e2))
{
int i = 0;
for (i = 0; i < sz - 1; i++)
{
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
//相邻两个元素比较
if (cmp((char*)base + j * width, (char*)base + (j + 1) * width) > 0)
{
//不满足条件交换两个元素
_swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
}
}
}
}
void print_arr(int* arr, int sz)
{
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int cmp_int(const void* e1, const void* e2)
{
return *(int*)e1 - *(int*)e2;
}
int main()
{
int arr[] = { 9,8,7,6,5,4,3,2,1 };
int sz = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, sz, sizeof(arr[0]), cmp_int);
print_arr(arr, sz);
return 0;
}