package com.study.data.structures.sort;
import java.util.Arrays;
public class HeapSort {
public static void main(String[] args) {
int[] arrays = new int[8000000];
for (int i = 0; i < 8000000; i++) {
arrays[i] = (int) (Math.random() * 8000000);
}
heapSort(arrays);
}
public static void heapSort(int[] arr) {
long startTime = System.currentTimeMillis();
int temp = 0;
for (int i = arr.length / 2 - 1; i >= 0; i--) {
adjustHeap(arr, i, arr.length);
}
for (int i = arr.length - 1; i > 0; i--) {
temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
adjustHeap(arr, 0, i);
}
long endTime = System.currentTimeMillis();
System.out.println("堆排序花费时间::" + (endTime - startTime));
}
public static void adjustHeap(int[] arr, int i, int length) {
int temp = arr[i];
for (int k = 2 * i + 1; k < length; k = 2 * k + 1) {
if (k + 1 < length && arr[k] < arr[k + 1]) {
k++;
}
if (arr[k] > temp) {
arr[i] = arr[k];
i = k;
} else {
break;
}
}
arr[i] = temp;
}
}
|