桶排序:工作的原理是將數組分到有限數量的桶里。每個桶再個別排序(可能在使用別的排序算法,我這里用的單向鏈表在放入時就排好了順序),最后依次把各個桶中的記錄列出來得到有序序列。分布均勻的一組數,用桶排序效率很高。
1.桶的個數是用這組數的個數確定的
2.每個數值入桶的位置(桶的下標),是由(數值*數組長度/(最大數值+1))這個確定的。
桶排序(BucketSort)概略圖
1.LinkedNode類
1 public class LinkedNode { 2 private int value; 3 private LinkedNode next; 4 5 public LinkedNode(int value) 6 { 7 this.value=value; 8 } 9 10 public int getValue() { 11 return value; 12 } 13 14 public void setValue(int value) { 15 this.value = value; 16 } 17 18 public LinkedNode getNext() { 19 return next; 20 } 21 22 public void setNext(LinkedNode next) { 23 this.next = next; 24 } 25 26 27 }
2.BucketSort類
1 import java.util.Arrays; 2 3 public class BucketSort { 4 //計算出入那桶(桶的下標) 5 public static int hash(int value,int length,int max) 6 { 7 return ((value*length)/(max+1)); 8 } 9 10 public static void main(String[] args) { 11 int arr[]= {1045,3434,3566,4325,3234,6545,8237,4540,1550,5653,43534}; 12 System.out.println("開始:"+Arrays.toString(arr)); 13 BucketSort.sort(arr); 14 System.out.println("最終;"+Arrays.toString(arr)); 15 } 16 17 public static void sort(int arr[]) 18 { 19 //1定義桶的大小 20 int length=arr.length; 21 LinkedNode bucket[]=new LinkedNode[length]; 22 //2求最大值 23 int max=arr[0]; 24 for(int i=1;i<length;i++) 25 { 26 if(arr[i]>max) 27 max=arr[i]; 28 } 29 //入桶 30 for(int i=0;i<length;i++) 31 { 32 int value=arr[i]; 33 //得到入桶的下標 34 int hash=hash(value,length,max); 35 if(bucket[hash]==null) 36 { 37 bucket[hash]=new LinkedNode(value); 38 }else { 39 insertInto(value,bucket[hash],bucket,hash); //桶有值時入桶方法 40 } 41 42 } 43 44 //出桶 45 int i=0; 46 for(LinkedNode node:bucket) 47 { 48 while(node!=null) 49 { 50 arr[i++]=node.getValue(); 51 node=node.getNext(); 52 } 53 } 54 55 56 } 57 58 59 public static void insertInto(int value,LinkedNode head,LinkedNode bucket[],int hash) 60 { 61 LinkedNode newNode=new LinkedNode(value); 62 if(value<head.getValue()) 63 { 64 newNode.setNext(head); 65 bucket[hash]=newNode; 66 return ; 67 } 68 LinkedNode p=head; 69 LinkedNode pre=null; 70 while(p!=null&&value>p.getValue()) 71 { 72 pre=p; 73 p=p.getNext(); 74 } 75 if(p==null) 76 { 77 pre.setNext(newNode); 78 }else { 79 pre.setNext(newNode); 80 newNode.setNext(p); 81 } 82 83 } 84 85 }
總結:
桶排序是以空間消耗換時間消耗,桶划分的越小,各個桶之間的數據越少,排序所用的時間也會越少,但相應的空間消耗就會增大。