//main.c文件
//编程实现qsort()函数功能
#include"qsort.h"
#include<string.h>
int compar_int(const void* p1, const void* p2)//整型大小的比较
{
return *(int*)p1 - *(int*)p2;
}
void test1()
{
int arr[10] = {13,43,6,8,2,78,435,123,34,68};
int sz = sizeof(arr) /sizeof(arr[0]);
my_qsort(arr, sz, sizeof(arr[0]), compar_int);****//此处报错:undefined reference to 'my_sqort'****
int i = 0;
for(i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int main()
{
test1();
return 0;
}
//qsort.h头文件
#include <stdio.h>
#include <stdlib.h>
void my_qsort(void* base, int sz, int width, int (*compar)(const void* p1, const void* p2));//冒泡排序函数(回调函数)
void Swap(char* buf1, char* buf2, int width);
//qsort.c文件
#include"qsort.h"
void Swap(char* buf1, char* buf2, int width)//交换两个元素,一个字节一个字节地交换
{
int i = 0;
for(i = 0; i < width; i++)
{
char temp = *buf1;
*buf1 = *buf2;
*buf2 = temp;
buf1++;
buf2++;
}
}
void my_qsort(void* base, int sz, int width, int (*compar)(const void* p1, const void* p2))//冒泡排序函数(回调函数)
{
int i = 0;
for(i = 0; i < sz - 1; i++)
{
int j = 0;
for(j = 0; j < sz - 1 - i; j++)
{
if(compar((char*)base + j * width, (char*)base + (j + 1) * width) > 0)
Swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
}
}
}
