zoukankan      html  css  js  c++  java
  • Bucket Sort

    (referrence: GeekforGeeks)

    Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the following problem. 
    Sort a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across the range. How do we sort the numbers efficiently?

    The lower bound for Comparison based sorting algorithm (Merge Sort, Heap Sort, Quick Sort, etc) is O(n log n).

    And, counting sort cannot be applied here as we use keys as index in counting sort.

    bucketSort(arr[], n)
    1) Create n empty buckets (Or lists).
    2) Do following for every array element arr[i].
    .......a) Insert arr[i] into bucket[n*array[i]]
    3) Sort individual buckets using insertion sort.
    4) Concatenate all sorted buckets.

    If we assume that insertion in a bucket takes O(1) time then steps 1 and 2 of the above algorithm clearly take O(n) time.

    The O(1) is easily possible if we use a linked list to represent a bucket.

    Step 4 also takes O(n) time as there will be n items in all buckets.

    The main step to analyze is step 3. This step also takes O(n) time on average if all numbers are uniformly distributed.

     1 class Solution {
     2     public static void bucketSort(int[] arr, int n) {
     3         // Create n empty buckets
     4         List<Integer>[] buckets = new ArrayList[n];
     5         for (int i = 0; i < n; i++)
     6             buckets[i] = new ArrayList<Integer>();
     7 
     8         for (int i = 0; i < arr.length; i++) {
     9             int index = n * arr[i];
    10             buckets[index].add(arr[i]);
    11         }
    12 
    13         // Sort buckets
    14         for (int i = 0; i < n; i++)
    15             Collections.sort(buckets[i]);
    16         // Connect buckets
    17         int p = 0;
    18         for (int i = 0; i < n; i++) {
    19             for (int j = 0; j < buckets[i].size(); j++) {
    20                 arr[index++] = b[i].get(j);
    21             }
    22         }
    23     }
    24 }
  • 相关阅读:
    回归分析举例
    用js实现在文本框中检测字数和限制字数功能
    深入理解CSS盒子模型
    CSS盒子模型小剖析
    iphone开发“关闭键盘的例子”
    最全的CSS浏览器兼容问题整理(IE6.0、IE7.0 与 FireFox)
    Soap UI 负载测试
    应聘时最漂亮的回答! 留着 早晚用的上 2012
    SOAP UI 简单使用
    乔布斯做管理的十条戒律
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4858174.html
Copyright © 2011-2022 走看看