前言:
排序算法有很多种,如选择排序、插入排序、冒泡排序、桶排序、快速排序等等。这里介绍的是简化版桶排序、冒泡排序和插入排序。
推荐一本算法入门书——《啊哈!算法》
1. 桶排序[简化版]:
原理:新建一个book数组用来标记原数组每一个数字出现的个数。
public static int[] bottomSort(int[] nums) {
int[] res = new int[nums.length];
int temp = nums[0];
for (int lang : nums)
temp = Math.max(temp, lang);
int[] book = new int[temp + 1];
for (int i = 0; i < nums.length; i++) {
book[nums[i]]++;
}
int z = 0;
for (int i = 0; i <= book.length - 1; i++) { //由小到大排序。
for (int j = 1; j <= book[i]; j++) {
res[z] = i;
z++;
}
}
return res;
}
桶排序的优缺点:
优点:
时间复杂度为O(M+N),运行非常快速。</