就来冒泡一下~写个冒泡排序玩玩~
写了个通用性较强的冒泡法排序~就是感觉输出样式需要的话可以改改~还有如果要进行二级排序则要另外写比较函数了~不过总体感觉还是不错的~原谅没啥时间写注释了~
程序代码:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<assert.h> #ifndef MY_SORT #define My_SORT #define List_Size sizeof(SqList) typedef struct SqList { void* Data; //抽象储存数据类型 void** Point; //抽象数据指针类型 size_t len; //数组长度 size_t size; //单位数组元素规模大小 }SqList,*PSqList; void Sort(void* a,size_t len,size_t Data_Size,int (*Comp)(void* a,void* b)); //创建一个节点 void Swap(void* a,void* b,size_t size); void Get_Data(PSqList L,void* a); void Fun(PSqList L,int (*Comp)(void* a,void* b)); //冒泡法排序 void Del_List(PSqList* L); void Del_Data(void** p); void Sort(void* a,size_t len,size_t Data_Size,int (*Comp)(void* a,void* b)) { PSqList L=NULL; size_t i=0; L=(PSqList)malloc(List_Size); assert(L!=NULL); memset(L,0,List_Size); L->size=Data_Size; L->len=len; L->Data=malloc(L->size*len); assert(L->Data!=NULL); memset(L->Data,0,L->size*len); memcpy(L->Data,a,Data_Size*len); L->Point=malloc(sizeof(void** )*L->len); assert(L->Point!=NULL); memset(L->Point,0,sizeof(void** )*L->len); for (i=0;i!=len;++i) L->Point[i]=(char* )L->Data+i*L->size; Fun(L,Comp); Get_Data(L,a); Del_List(&L); } void Get_Data(PSqList L,void* a) { size_t i=0; for (i=0;i!=L->len;++i) memcpy((char* )a+i*L->size,(char* )L->Point[i],L->size); } void Swap(void* a,void* b,size_t size) { size_t t=0; memcpy(&t,a,size); memcpy(a,b,size); memcpy(b,&t,size); } void Fun(PSqList L,int (*Comp)(void* a,void* b)) { size_t i=0; size_t j=0; for (i=0;i<L->len;++i) for (j=0;j<L->len-i-1;++j) if ((*Comp)((char* )L->Point[j],(char* )L->Point[j+1])==1) Swap(L->Point[j],L->Point[j+1],L->size); } void Del_Data(void** p) { if (*p==NULL) return ; free(*p); *p=NULL; } void Del_List(PSqList* L) { if (*L==NULL) return ; Del_Data(&(char* )(*L)->Point); Del_Data(&(*L)->Data); Del_Data(L); } #endif
程序代码:
#include"Sort.h" #include<time.h> #define NUM 10 typedef int ElemType; int Comp(void* a,void* b); void Init(ElemType a[]); void Print(ElemType a[]); int main() { ElemType a[NUM]={0}; Init(a); Print(a); Sort(a,NUM,sizeof(ElemType),Comp); Print(a); return 0; } int Comp(void* a,void* b) { ElemType at=*(ElemType*)a; ElemType bt=*(ElemType*)b; if (at>bt) return 1; if (at<bt) return -1; return 0; } void Init(ElemType a[]) { int i=0; srand((unsigned )time(NULL)); for (i=0;i!=NUM;++i) a[i]=rand()%(NUM*10); } void Print(ElemType a[]) { int i=0; for (i=0;i!=NUM;++i) printf("%-4d ",a[i]); puts(""); }
[此贴子已经被作者于2017-5-8 19:22编辑过]