用c 编程基数排序、归并排序代码?
基数排序#include #include using namespace std; struct Node{ int data; Node *prior; Node *next; }; void createlinklist(Node* &L){ Node *p; Node *q; L=new Node; L->next=NULL; L->prior=NULL; //q=new Node; /* 无用 zhjiemm */ //p = new Node; /* 无用 zhjiemm */ //p->next=NULL; /* 无用 zhjiemm */ int adata=0; q=L;...全部
基数排序#include #include using namespace std; struct Node{ int data; Node *prior; Node *next; }; void createlinklist(Node* &L){ Node *p; Node *q; L=new Node; L->next=NULL; L->prior=NULL; //q=new Node; /* 无用 zhjiemm */ //p = new Node; /* 无用 zhjiemm */ //p->next=NULL; /* 无用 zhjiemm */ int adata=0; q=L; while(adata!=-1){ p= new Node; p->data=adata; p->prior=NULL; p->next=NULL; p->prior=q; q->next=p; q=p; cin>>adata; if(adata==-1){ L=L->next; q->next=L; L->prior=q; } } } //**************************************************** //子函数 // getNode() Node* getNode(Node* &L){ /********** 全部改写 ********** zhjiemm */ Node *p; p=L->next; if(p!=L){ L->next = p->next; p->next->prior = L; }else{ p=NULL; } return p; } //getNumber() int getNumber(Node *p,int i){ int pdata,k; pdata=p->data; k=(int)(pdata/pow(10,i)); return k; } //addNode() void addNode(Node* &lhead,Node *p){ p->prior=lhead->prior; p->next=lhead; lhead->prior->next=p; lhead->prior=p; } //append() void append(Node* &L,Node* lhead){ if(lhead->next != lhead){//不为空 L->prior->next=lhead->next; /********** 指针指错了 ********** zhjiemm */ lhead->next->prior=L->prior; lhead->prior->next=L; L->prior=lhead->prior; } } //**************************************************** //基数排序主函数 void radix_sort(Node *&L,int k){ Node *Lhead[10],*p; int i,j,flag; coutnext=Lhead[j]->prior=Lhead[j]; while(L->next!=L){//L中的数放入lhead[n]中 p=getNode(L); if(p) /********** 判断一下不为空 ********** zhjiemm */ { flag=getNumber(p,i);//第n轮,取倒数第n位数 addNode(Lhead[flag],p); } } for(int m=0;mnext; /* 初始值不对 zhjiemm */ while(p!=L){ coutnext; } return 0; }//归并排序中之并int *Merge(int *a,int aLength,int *b,int bLength){ //合并结果指针 int *result; //初始化结果指针 result=new int[aLength bLength]; int i=0,j=0,k=0; //定义左指针 a=new int[aLength]; //定义右指针 b=new int[bLength]; //元素排序,左右比较 while(i if(a[i] result[k ]=a[i ];//将小的赋值到结果 } else{//左元素大于右元素 result[k ]=b[j ];//将小的赋值到结果 } } while(i result[k ]=a[i ]; } while(j result[k ]=b[j ]; } return result;}//归并排序中之归拆分//Updated by zivsoft at 05/06/2009int *Split(int *data,int length){ int i=0,j=0,k=0; int *left,*right,*result; //取中间下标 int middle=length/2; left=new int[middle]; right=new int[middle]; //初始化有序结果数组 result=new int[length]; //如果数组只有一个元素,直接返回,无需排序 if(length return data; } int rightLength=0; //奇数个元素的话,重新分配右数组长度 if(length%2!=0){ delete[] right; rightLength=middle 1; right=new int[rightLength]; } //拆分数组 for(k=0;k if(i left[i ]=data[k]; } else{ right[j ]=data[k]; } } left=Split(left,i);//递归拆分左数组 right=Split(right,rightLength);//递归拆分右数组 result=Merge(left,i,right,rightLength);//排序并合并 //printarray(result,k); //输出,供lihua(zorywa)侧使用(zivsoft) return result;}。
收起