自定义qsort实现排序1
开发原因:为更好的实现PAT德才论及以后的测试题目,设计独立的排序代码,参看了别人的德才论答案,发现在用qsort函数。我认为测试题主要测试手敲代码的能力,所以自己利用简单的冒泡法设计myqsort代码,实现各种变量类型的排序。
思路:
1、创建myswap函数,实现按照字节交换两个元素次序
2、实现满足int,double等类型的myqsort排序函数
#include<stdio.h>
#include<stdlib.h>
/*测试用例*/
double arr[5] = {2.2,14.5,9.1,8.6,5.3};//2 5 8 9 14
//char arr[11] = {2,14,9,8,5,7,29,31,85,12,36};//2 5 8 9 14
//int arr[11] = {2,14,9,8,5,7,29,31,85,12,36};//2 5 8 9 14
//比较函数 返回负数,代表小的在前,大的在后顺序 , return<0 elem1将被排在elem2前面
int compar_charfun(const void* a,const void* b)
{
return (*(char*)a-*(char*)b);
}
int compar_shortfun(const void* a,const void* b)
{
return (*(short*)a-*(short*)b);
}
int compar_intfun(const void* a,const void* b)
{
return (*(int*)a-*(int*)b);
}
int compar_doublefun(const void* a,const void* b)
{
return *(double *)a > *(double *)b ? 1 : -1;
}
void myswap(void* a,void* b,unsigned int byte_size)//按照字节交换
{
int i;
char temp;
for(i=0;i<byte_size;i++)
{
temp = *((char*)a+i);
*((char*)a+i)= *((char*)b+i);
*((char*)b+i) = temp;
}
}
void mysort(void *arrin, unsigned int arrsize ,unsigned int byte_size,int (*compar)(const void*,const void*))
{
printf("arrsize:%d\n",sizeof(arr)/sizeof(arr[0]));
switch (byte_size)
{
case sizeof(char)://char
#undef type
#ifndef type
#define type char
#endif
printf("case char:%d\n\n",sizeof(type));
{
type* array = arrin;
unsigned int i,j,temp;
printf("maopao char:%d\n\n",sizeof(type));
for(i=0;i<arrsize-1;i++)
{
for(j=0;j<arrsize-1-i;j++)
{
if(compar(&array[j+1],&array[j])<0)
{
myswap(&array[j],&array[j+1],sizeof(char));
}
}
}
}
break;
case sizeof(short)://short
#undef type
#ifndef type
#define type short
#endif
printf("case short:%d\n\n",sizeof(type));
{
type* array = arrin;
unsigned int i,j,temp;
printf("maopao short:%d\n\n",sizeof(type));
for(i=0;i<arrsize-1;i++)
{
for(j=0;j<arrsize-1-i;j++)
{
if(compar(&array[j+1],&array[j])<0)
{
myswap(&array[j],&array[j+1],sizeof(short));
}
}
}
}
break;
case sizeof(int)://int
#undef type
#ifndef type
#define type int
#endif
printf("case int:%d\n\n",sizeof(type));
{
type* array = arrin;
unsigned int i,j,temp;
printf("maopao int:%d\n\n",sizeof(type));
for(i=0;i<arrsize-1;i++)
{
for(j=0;j<arrsize-1-i;j++)
{
if(compar(&array[j+1],&array[j])<0)
{
myswap(&array[j],&array[j+1],sizeof(int));
}
}
}
}
break;
case sizeof(double)://double
#undef type
#ifndef type
#define type double
#endif
printf("case double:%d\n\n",sizeof(type));
{
type* array = arrin;
unsigned int i,j,temp;
printf("maopao double:%d\n\n",sizeof(type));
for(i=0;i<arrsize-1;i++)
{
for(j=0;j<arrsize-1-i;j++)
{
if(compar(&array[j+1],&array[j])<0)//从小到大排序
{
myswap(&array[j],&array[j+1],sizeof(double));
}
}
}
}
break;
default:
printf("参数错误\n");
break;
}
}
int main(void)
{
unsigned int i;
mysort(arr,sizeof(arr)/sizeof(arr[0]),sizeof(double),compar_doublefun);
for(i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
printf("%lf ",arr[i]);
}
return 0;
}
不足之处:过多的宏定义