本文将围绕冒泡排序、桶排序、计数排序、堆排序、插入排序、并归排序、快速排序和选择排序,按照描述、时间复杂度(最坏情况)、动态图展示和代码实现来讲解。本文默认排序为从小到大。
本文相关代码已上传至github,欢迎关注https://github.com/zhuzhenke/common-algorithms
公用方法
SortUtils
public class SortUtils {
public static void check(int[] sortingData) {
if (sortingData == null || sortingData.length == 0) {
throw new IllegalArgumentException("sortingData can not be empty!");
}
}
public static void swap(int[] swapArray, int i, int j) {
check(swapArray);
if (i < 0 || i > swapArray.length - 1) {
throw new ArrayIndexOutOfBoundsException("illegal index i:" + i);
}
if (j < 0 || j > swapArray.length - 1) {
throw new ArrayIndexOutOfBoundsException("illegal index j:" + j);
}
int temp = swapArray[i];
swapArray[i] = swapArray[j];
swapArray[j] = temp;
}
public static int getMaxValue(int[] sortingData) {
check(sortingData);
int max = sortingData[0];
for (int value : sortingData) {
if (value < 0) {
throw new IllegalArgumentException("value could not be negative:" + value);
}
if (value > max) {
max = value;
}
}
return max;
}
}
冒泡排序
描述
- 比较前后两个数的大小,如果前者大于后者,则交换两个数的位置
- 最大的数字在进行一轮比较和交换后,会出现在数组的最后一个位置
- 每一轮之后,可减少最大数字的比较。重复上述操作直到没有需要比较的元素为止
时间复杂度
O(n^2)
动态图展示
代码实现
public int[] sort(int[] sortingData) {
SortUtils.check(sortingData);
for (int j = sortingData.length - 1; j > 0; j--) {
for (int i = 0; i < j; i++) {
if (sortingData[i] > sortingData[i + 1]) {
SortUtils.swap(sortingData, i, i + 1);
}
}
}
return sortingData;
}
桶排序
描述
- 挑选数组中最大的数字,设置默认分配的桶数,得到每个桶容纳的数字范围。如最大是10,桶是4个,则每个桶最大容纳3个数字。第0个桶放0、1、2、3,第1个桶方4、5、6,第2桶方7,8,9,以此类推
- 对每个桶内进行冒泡排序或选择排序
- 遍历所有桶,依次取出每个桶中的元素,得到的就是一个排好序的数组
时间复杂度
O(n^2)