五大类内部排序算法
- 插入排序
- 交换排序
- 选择排序
- 归并排序
- 基数排序
简单选择排序: SelectSort
算法思路
- 选择排序一共有[数组大小-1]轮排序
- 每一轮排序, 又是一个循环, 循环的规约如下
- 先设定当前的这个数是最小值
- 与后面的数据逐个比较, 选出本轮最小的数值, 并且用 minIndex 和 minValue 分别记录下它的下标和值
- 与本轮设置的最小值进行交换位置[即与本轮循环的首位置进行交换]
实现
package com.com.beyond.dhl.utils.sort;
import java.util.Arrays;
public class SelectSort {
public static void main(String[] args) {
int[] arr = {
1, 5, 3, 2, 6, 7, 0, -3};
System.out.println(Arrays.toString(arr));
selectSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void selectSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
int minValue = arr[i];
for (int x = i + 1; x < arr.length; x++) {
if (arr[x] < arr[i]) {
minIndex = x;
minValue = arr[x];
}
}
if (minIndex != i) {
arr[minIndex] = arr[i];
arr[i] = minValue;
}
}
}
}
简单选择排序 测试80000个随机数据的排序效率
public static void main(String[] args) {
int[] test = new int[80000];
for (int i = 0; i < test.length; i++) {
test[i] = (int) (Math.random() * 1000000);
}
long start = System.currentTimeMillis();
selectSort(test);
long end = System.currentTimeMillis();
System.out.println("80000个随机数使用简单选择排序所耗时间为: " +(end - start) / 1000 + "秒");
}

堆排序: HeapSort
算法思路:
- 将待排序序列构成一个大顶堆
- 此时, 整个序列的最大值就是堆顶的根节点
- 将其与末尾元素进行交换, 此时末尾就是最大值
- 然后将剩下的n-1个元素重新构造成一个堆, 只需要从 0 开始调用 调整堆(adjustHeap)方法即可
[因为在之前第一步已经将该堆调整成了大顶堆, 交换数据只是与最后一个数据节点交换, 这是最后一个变为了第一个节点,我们调整该节点即可达到目的]
, 循环执行 n-1 次 交换与调整, 便可以得到一个有序序列了.
实现:
package com.com.beyond.dhl.utils.sort;
public class HeapSort {
public static void main(String[] args) {
int[] arr = {
1, 5, 3, 2, 6, 7, 0, -3};
heapSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void heapSort(int[] arr) {
int temp = 0;
for (int i = arr.length / 2 - 1; i >= 0; i--) {
adjustHeap(arr, i, arr.length);
}
for (int j=arr.length-1; j>0;j--){
temp = arr[j];
arr[j] = arr[0];
arr[0] = temp;
adjustHeap(arr, 0, j);
}
}
public static void adjustHeap(int[] arr, int nodeValue, int length) {
int temp = arr[nodeValue];
for (int k = nodeValue * 2 + 1; k < length; k = nodeValue * 2 + 1) {
if (k + 1 < length && arr[k] < arr[k + 1]) {
k++;
}
if (arr[k] > temp) {
arr[nodeValue] = arr[k];
nodeValue = k;
arr[nodeValue] = temp;
} else {
break;
}
}
}
}
堆选择排序 测试八百万个随机数据的排序效率 (还是快排更胜一筹)
public static void main(String[] args) {
int[] test = new int[8000000];
for (int i = 0; i < test.length; i++) {
test[i] = (int) (Math.random() * 1000000);
}
long start = System.currentTimeMillis();
heapSort(test);
long end = System.currentTimeMillis();
System.out.println("8百万个随机数使用堆排序所耗时间为: " +(end - start) + "毫秒");
}
