#include<stdio.h>
#include<string.h>
int compare_int(void *a,void *b);
int compare_str(void *a,void *b);
void swap(char *a,char *b,int len);
void sort(void *front,int n,int len,int (*pfunc)(void *,void *));
void showarr(void *front,int n,char *type);//将数组元素类型作为形参是笨办法
int main(){
int arr1[]={231,4,23,31,412,312,31,312,3123,123,112,31,23,1223,1253,5123,1623,12,32,3,23,223,12,321,34,21,5,12,645,51,25,76,547,47,4546,454,34,23,623,2,23};
char *arr2[]={"sddwa","dsad","csa","dsa","fas","dasdf","gf","hr","rewq","vcb","fd1","h","ew","fd","v","a","csd","fs","ig","w","vxcv","dfg","w","qw","bng","j","t","er","ger"};
fputs("The arr before:->\n",stdout);
showarr(arr1,sizeof(arr1)/sizeof(*arr1),"int");
showarr(arr2,sizeof(arr2)/sizeof(*arr2),"str");
sort(arr1,sizeof(arr1)/sizeof(*arr1),sizeof(int),compare_int);
sort(arr2,sizeof(arr2)/sizeof(*arr2),sizeof(char *),compare_str);
fputs("\nThe arr after:->\n",stdout);
showarr(arr1,sizeof(arr1)/sizeof(*arr1),"int");
showarr(arr2,sizeof(arr2)/sizeof(*arr2),"str");
return 0;}
//
int compare_int(void *a,void *b){//a,b为指向数组元素(int)的指针
return *(int *)a-*(int *)b;}
int compare_str(void *a,void *b){//a,b为指向数组元素(字符指针)的指针
return strcmp(*(char **)a,*(char **)b);}
void swap(char *a,char *b,int len){
for(;len-->0;){
char temp=*a;
*a++=*b;
*b++=temp;
}
}
void sort(void *front,int n,int len,int (*pfunc)(void *,void *)){
for(char *i=(char *)front,*rear=(char *)front+(n-1)*len;i<rear;i+=len)
for(char *j=i+len;j<=rear;j+=len)
if(pfunc(i,j)>0) swap(i,j,len);
}
void showarr(void *front,int n,char *type){
if(!strcmp(type,"int")) for(int *p=(int *)front;n-->0;printf("%d ",*p),p++);
else if(!strcmp(type,"str")) for(char **p=(char **)front;n-->0;printf("%s ",*p),p++);
fputs("\b.\n",stdout);
}
?
|