基数排序是基于桶排序实现的,总之基本思想是:先基于个位进行桶排序,更新原序列;再基于十位进行桶排序,更新原序列……
code1:java
import java.util.*; public class JavaTest1 { public static void main(String[] args) { int a[]={1,255,8,6,25,47,14,35,58,75,96,158,657}; bucketsort(a); showset(a); } public static void showset(int[] b) { for(int i=0;i<b.length;i++) { System.out.print(" "+b[i]); } System.out.println(""); } public static void bucketsort(int[] data) { int n=data.length; LinkedList<Integer>[] basket=new LinkedList[10]; for(int i=0;i<10;i++) { basket[i]=new LinkedList<Integer>(); } int maxlen=-1; for(int i=0;i<n;i++) { if(Integer.toString(data[i]).length()>maxlen) { maxlen=Integer.toString(data[i]).length(); } } for(int i=maxlen-1;i>=0;i--) { for(int j=0;j<n;j++) { String str=""; int len=Integer.toString(data[j]).length(); while(len<maxlen) { str+="0"; len++; } str+=Integer.toString(data[j]); basket[str.charAt(i)-'0'].add(data[j]); } int pos=0; for(int k=0;k<10;k++) { try { while(true) { data[pos]=basket[k].removeFirst(); pos++; } } catch(NoSuchElementException e) { } } showset(data); } } }
代码的基本思想:
先进行个位排序,再进行十位排序,再进行百位排序……
code2:C++
/*============================== 9 name: radix sort -------------------------------- time complexity: average O(2dn) -------------------------------- space complexity: O(n) -------------------------------- stability: stable ==============================*/ void refresh_data(std::vector<int> &a, std::vector<std::vector<int>> &sto) { std::vector<int>::iterator it,it1; std::vector<std::vector<int>>::iterator it2; it=a.begin(); it2=sto.begin(); while(it!=a.end() && it2!=sto.end()) { it1=(*it2).begin(); while(it1!=(*it2).end()) { *it=*it1; it1++; it++; } (*it2).clear(); it2++; } return; } //suppose:there are no minus number void radix_sort(std::vector<int> &a) { std::vector<std::vector<int>> sto; sto.resize(10); int max=0; std::vector<int>::iterator it=a.begin(); while(it!=a.end()) { int idx; if(max<*it) { max=*it; } idx=(*it)%10; sto[idx].push_back(*it); it++; } refresh_data(a,sto); int d=0; int temp=max; while(1) { if(temp!=0) { d++; } else { break; } temp/=10; } for(int i=1;i<=d;i++) { int div=pow(10.0,i); it=a.begin(); while(it!=a.end()) { int idx; idx=(*it/div)%10; sto[idx].push_back(*it); it++; } refresh_data(a,sto); } return; }