常用排序算法总结(五)

来源:互联网 发布:windows驱动器被锁定 编辑:程序博客网 时间:2024/05/15 11:08

5 基数排序

   基数排序是一种非常独特的排序方式。它不需要把序列中的元素进行相互比较。只要把原序列进行几次拆分跟合并就能完成排序。

  例如: 一个序列:12 137 8 7564,先对个位数调整:12 7564 137 8,在对十位数进行调整:08 12 137 7564,对百位调整:008 012 137 7564 ,在对千位进行调整:0008 0012 0137 7564,排序完成。

  时间复杂度:O(d*n)


  使用基数排序对单链表进行排序:

  使用一个指针数组,把一个单链表按基数链接成为10种不同的单链表,链表的头指针放在对应的数组中。

 

 

 

  C语言

//24K丶小烦#include<stdio.h>#include<stdlib.h>//链表结点typedef struct Node{int value;struct Node *next;}Node, *List;//构造单链表void CreateList(List &pHead,int data){if(!pHead){pHead=(List)malloc(sizeof(Node));pHead->value=data;pHead->next=NULL;}else{List param=pHead;while(param->next)param=param->next;param->next=(List)malloc(sizeof(Node));param->next->value=data;param->next->next=NULL;}}void RandNode(List &pHead,int length){for(int i=0;i<length;i++)CreateList(pHead,rand());}//打印单链表void ShowNode(List list){while(list){printf("%d\n",list->value);list=list->next;}}//对桶就行链接void Collect(List *list,List &pHead){List temp=NULL;for(int i=0;i<10;i++){if(list[i]){if(!pHead)temp=pHead=list[i];elsetemp->next=list[i];while(temp->next)temp=temp->next;}}temp->next=NULL;for(i=0;i<10;i++)list[i]=NULL;}//将链表链接到多个桶中void Distribute(List *list,int radix,List &p){List temp=p;List pHead=NULL,l=NULL;int index=0;while(temp){index=(temp->value/radix)%10;//求基数l=temp->next;temp->next=NULL;if(!list[index])list[index]=temp;else{pHead=list[index];while(pHead->next)pHead=pHead->next;pHead->next=temp;}temp=l;}p=NULL;Collect(list,p);}//基数排序void RadixSort(List &list,int count){List array[10];for(int i=0;i<10;i++)array[i]=NULL;   //初始化桶int radix=1;for(i=0;i<count;i++){Distribute(array,radix,list);radix*=10;}}int main(){List pHead=NULL;RandNode(pHead,100);RadixSort(pHead,5);ShowNode(pHead);return 0;}

  源码下载

0 0
原创粉丝点击