我们以前写排序算法,一般都是以数组作为参数,或者是某种特定的结构体作为参数,但是这样设计的算法不通用。那么我们怎么实现更为通用的算法呢? 这样设计的算法对更多的数据结构通用,可以自己实现比较规则。。。。。。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//交换两个元素
void swap(void *x, void *y, int length){
//char t[length];
char *t = (char*)malloc(length);
memcpy(t,x, length);
memcpy(x,y,length);
memcpy(y,t,length);
free(t);
}
//冒泡排序 addr: 元素首地址 length:元素长度 size:元素个数 compare:自定义比较规则
void bubble_sort(void* addr, int length, int size ,int(*compare)(void*, void *)){
int i, j;
for(i = 0; i<size-1; i++){
for(j = 1; j<size-i; j++){
void *front =(char*)addr+(j-1)*length;
void *behind = (char*)addr+j*length;
if(compare(front, behind)>0){
swap(front, behind, length);
}
}
}
}
//插入排序 addr: 元素首地址 length:元素长度 size:元素个数 compare:自定义比较规则
void insert_sort(void* addr, int length, int size, int(*compare)(void *, void *)){
int i, j;
for(i = 0; i<size-1; i++){
for(j = i+1; j>0; j--){
void *front = (char*)addr+(j-1)*length;
void *behind = (char*)addr+j*length;
if(compare(front, behind)<=0){
break;
}
swap(front, behind, length);
}
}
}
//快排 addr: 元素首地址 length:元素长度 compare:自定义比较规则 left:左下标 right:右下标
void quick_sort(void *addr, int length, int(*compare)(void *, void *), int left, int right){
int i, j;
void *x, *ai, *aj;
x = (char*)addr + length*left; //首地址
if(left<right){
i = left+1;
j = right;
while(i<j){
aj = (char*)addr+length*j; //每次修改了i 的值就要重新寻址
ai = (char*)addr+length*i;
/*while(i<j && compare(aj,x)>=0){
// j--;
// aj = (char*)addr+length*j;
// printf("j=%d\n", j);
//}
while(i<j && compare(ai,x)<=0){
i++;
ai = (char*)addr+length*i;
printf("i=%d\n", i);
}
if(i<j){
swap(ai, aj, length);
}
*/
if(compare(ai, x)>0){
swap(ai,aj, length);
j--;
}else{
i++;
}
}
aj = (char*)addr+length*j; //每次修改了i 的值就要重新寻址
ai = (char*)addr+length*i;
if(compare(ai, x)>=0){
i--;
}
aj = (char*)addr+length*j;
ai = (char*)addr+length*i;
swap((void*)((char*)addr+length*i), x, length);
quick_sort(addr, length, compare, left, i);
quick_sort(addr, length, compare,j , right);
}
}
//希尔排序 addr: 元素首地址 length:元素长度 size:元素个数 compare:自定义比较规则 increment:奇数增量
void shell_sort(void* addr, int length, int size,int(*compare)(void*,void*), int increment){
int k,i, j;
for(k = increment; k>=1; k = k-2, increment -= 2){
for(i = increment; i< size; i++)
for(j = i; j>=increment; j-=increment){
void *front = (char*)addr+(j-increment)*length;
void *behind = (char*)addr+j*length;
if(compare(front, behind)<=0){
break;
}
swap(front, behind, length);
}
}
}
int cmp_int(void *x, void *y){
return *((int*)x)-*((int*)y);
}
int cmp_string(void *x, void *y){
char **a =(char **)x;
char **b = (char **)y;
return strcmp(*a,*b);
}
int main(){
int i;
int a[] = {5,4,3,2,1,8,7,6,5,4,3,2,1};
char* b[] = {"tom","zb","blank","space","cn"};
quick_sort(a,sizeof(int),cmp_int, 0, 12);
for(i = 0; i<13; i++){
printf("result=%d\n", a[i]);
}
//insert_sort(b,sizeof(char *), 5, cmp_string);
//for(i = 0; i<5; i++){
// printf("%s\n", b[i]);
// }
//printf("%s", test);
}
其实今天是来做外链的
http://mrblankspace.cn