排序算法之Bucket Sort
来源:互联网 发布:数据集市的作用 编辑:程序博客网 时间:2024/05/17 05:13
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?
A simple way is to apply a comparison based sorting algorithm. Thelower bound for Comparison based sorting algorithm (Merge Sort, Heap Sort, Quick-Sort .. etc) is Ω(n Log n), i.e., they cannot do better than nLogn.
Can we sort the array in linear time? Counting sort can not be applied here as we use keys as index in counting sort. Here keys are floating point numbers.
The idea is to use bucket sort. Following is bucket algorithm.
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.
Following diagram (taken from CLRS book) demonstrates working of bucket sort.
Time Complexity: 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 (In the following code, C++ vector is used for simplicity). 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 (please referCLRS book for more details)
void bucketSort(float arr[], int n){ // 1) Create n empty buckets vector<float> b[n]; // 2) Put array elements in different buckets for (int i=0; i<n; i++) { int bi = n*arr[i]; // Index in bucket b[bi].push_back(arr[i]); } // 3) Sort individual buckets for (int i=0; i<n; i++) sort(b[i].begin(), b[i].end()); // 4) Concatenate all buckets into arr[] int index = 0; for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j];}
- 排序算法之Bucket Sort
- 排序算法总结之桶排序 Bucket Sort
- 算法总结系列之六: 桶排序(Bucket Sort)
- 算法学习之Bucket Sort
- 经典排序算法 - 桶排序Bucket sort
- 经典排序算法 - 桶排序Bucket sort
- 桶排序(Bucket Sort)----(排序算法七)
- 经典排序算法 - 桶排序Bucket sort
- 经典排序算法 - 桶排序Bucket sort
- 经典排序算法 - 桶排序Bucket sort
- 经典排序算法 - 桶排序Bucket sort
- 算法数据结构C++ - Bucket Sort 吊桶排序
- 排序之线性排序(counting sort, radix-sort, bucket-sort)
- 算法排序之最简单最快的排序--桶排序(Bucket Sort)
- 数据结构实验之排序三:bucket sort
- 数据结构实验之排序三:bucket sort
- 数据结构实验之排序三:bucket sort
- 数据结构实验之排序三:bucket sort
- JSP/Servlet-----10、JSP2的自定义标签
- iOS开发学习之C语言---C10 函数指针-3
- iOS开发学习之C语言---C11 二维数组、字符串数组、多维数组
- 值得推荐的C/C++框架和库
- leetcode15 3Sum
- 排序算法之Bucket Sort
- 二维数组查询
- samsung s3 gt-19300 开发 键盘回车事件
- 设计模式——行为型模式
- iOS中操作SQLite数据库
- 使用struts2+MySQL做简单的登录验证
- Xcode升级到7.1出现itms-90049 错误 的解决办法
- 2006年浙江大学1019简单计算器代码(栈的使用)
- Jsoup获取网页源代码不一致的问题