BucketSort

Bucket sort, or bin sort, is a sorting algorithm that works by partitioning an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a distribution sort, and is a cousin of radix sort in the most to least significant digit flavour. Bucket sort is a generalization of pigeonhole sort. Since bucket sort is not a comparison sort, the Ω(n logn) lower bound is inapplicable. The computational complexity estimates involve the number of buckets.

Bucket sort works as follows:

  1. Set up an array of initially empty "buckets."
  2. Scatter: Go over the original array, putting each object in its bucket.
  3. Sort each non-empty bucket.
  4. Gather: Visit the buckets in order and put all elements back into the original array.
 1 /*
 2  * Average    Worst     Memory   Stable
 3  *  n+k        n^2       n*k       Yes
 4 */
 5 public class BucketSort {
 6 
 7     public static void bucketSort(int[] a,int min,int max){
 8         Node[] nodes=new Node[a.length];
 9         for(int i=0;i<a.length;i++){
10             int v=a[i];
11             int bucketIndex=a.length * (v-min)/ (max-min+1);
12             if(nodes[bucketIndex]==null){
13                 nodes[bucketIndex]=new Node(v);
14             }
15             else{
16                 Node prev=null;
17                 Node node=nodes[bucketIndex];
18                 while(node != null && v>node.value){
19                     prev=node;
20                     node=node.next;
21                 }
22                 if(prev == null){
23                     nodes[bucketIndex]=new Node(v, node);
24                 }
25                 else{
26                     prev.next=new Node(v,node);
27                 }
28             }
29         }
30         
31         for(int i=0,j=0;i<nodes.length;i++){
32             Node node = nodes[i];
33             while (node != null) {
34                 a[j++] = node.value;
35                 node = node.next;
36             }
37         }
38     }
39     
40     public static class Node{
41         private int value;
42         private Node next;
43         Node(int value){
44             this.value=value;
45         }
46         Node(int value, Node next){
47             this.value=value;
48             this.next=next;
49         }
50     }
51     
52     public static void printArray(int[] a){
53         for(int i = 0;i < a.length;i++){
54             System.out.print(a[i]+" ");
55         }
56     }
57     
58     public static void main(String[] args) {
59         int[] input = new int[] {7, 5, 13, 12, 3, 8, 0, 3, 15, 4}; 
60         bucketSort(input, 0, 15);
61         printArray(input);
62 
63     }
64 
65 }

 

posted on 2013-03-31 11:57  melotang  阅读(139)  评论(0)    收藏  举报