算法之简单版桶排序
1、原理讲解
桶排序可以这样理解,例如我们要对0-100范围之内的数进行排序,那么我们首先准备101只桶,并将这些桶从0-100分别编上号。
准备好了桶,现在我有 50 4 18 18 37这一组数据,现在开始排序,首先是数字50,那么我们就将50放入编号为50的桶内,4放入编号为4的桶内,18放入编号为18的桶,18继续放入编号为18的桶,37放入编号为37的桶。
最后的结果是编号4的桶内有一个数,编号号为18的桶内有两个数,编号为37的桶内有一个数,编号为50的桶内有一个数。
然后我们会发现桶自身的编号代表了数字本身的大小,那么我们只要把这些桶一次遍历一遍,就可以将以上的数据进行从小到大的排序
2、代码实现
以下代码是简单版的桶排序的实现,分别有升序和降序
package com.maple.bucketsort;
import java.io.IOException;
/**
* simple bucket sort
* @author RhymeChiang
* @date 2017/12/01
**/
public class BucketSortSimple {
/**
* sort int array frm big to small between 0 and (maxBuckets-1)
* @param maxBuckets the number of buckets
* @param sort source data to be sort
*/
public static void sortAsc(int maxBuckets,int sort[]) throws IOException {
int [] sortedArray = new int[maxBuckets];
//read sortNumber number
for (int i = 0;i<sort.length;i++){
int num = sort[i];
sortedArray[num]++;
}
//print the sorted result from sortedArray
for(int j =0 ;j<maxBuckets;j++){
for(int k = 0;k<sortedArray[j];k++){
System.out.print(j+"\t");
}
}
}
/**
* desc sort
* @param maxBuckets
* @param sort
* @throws IOException
*/
public static void sortDesc(int maxBuckets,int sort[]) throws IOException {
int [] sortedArray = new int[maxBuckets];
//read sortNumber number
for (int i = 0;i<sort.length;i++){
int num = sort[i];
sortedArray[num]++;
}
//print the sorted result from sortedArray
for(int j =maxBuckets-1;j>=0;j--){
for(int k = 0;k<sortedArray[j];k++){
System.out.print(j+"\t");
}
}
}
public static void main(String[] args) throws IOException {
System.out.println("asc sort");
sortAsc(100,new int[]{50,4,18,18,37});
System.out.println("\ndesc sort");
sortDesc(100,new int[]{50,4,18,18,37});
}
}
4、实验结果
5、算法复杂度分析
第一个循环循环了n次,第二个嵌套循环循环了m+n次
所以时间复杂度O(m+2n)
6、算法优缺点分析
优点:速度快
缺点:资源利用率不高,需要占用大量的空间