2025-01-21 堆排序
This commit is contained in:
parent
a2342522af
commit
6036289d17
108
src/dataANDcalc/java/tree/HeapSort.java
Normal file
108
src/dataANDcalc/java/tree/HeapSort.java
Normal file
@ -0,0 +1,108 @@
|
||||
package tree;
|
||||
|
||||
public class HeapSort {
|
||||
|
||||
private int[] arr;
|
||||
|
||||
public HeapSort(int[] arr){
|
||||
this.arr = arr;
|
||||
}
|
||||
|
||||
private void heapSort(){
|
||||
// 第一个非叶子结点为 arr.length/2 - 1
|
||||
// 将整个排序队列变成大顶堆
|
||||
for(int i = arr.length/2 - 1; i>=0; i--){
|
||||
transHeap(arr, i, arr.length);
|
||||
}
|
||||
// 此时的队列已经是大顶堆了,根节点已经是最大的元素,所以队列长度从 arr.length - 1 开始
|
||||
for(int i = arr.length - 1; i>0; i--){
|
||||
// 将根节点和最后一个节点进行交换
|
||||
swap(0, i);
|
||||
transHeap(arr, 0, i);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用递归的方式完成堆排序
|
||||
*/
|
||||
private void heapSort2(){
|
||||
int length = arr.length;
|
||||
while(true){
|
||||
if(length == 1){
|
||||
break;
|
||||
}
|
||||
for(int i = length/2 - 1; i>=0; i--){
|
||||
transHeap2(i, length, arr[i]);
|
||||
}
|
||||
swap(0, length - 1);
|
||||
length--;
|
||||
}
|
||||
}
|
||||
|
||||
private void transHeap(int[] arr, int index, int length){
|
||||
int temp = arr[index];
|
||||
int tempIndex = index * 2 + 1;
|
||||
while(tempIndex < length){
|
||||
if(tempIndex + 1< length && arr[tempIndex+1] > arr[tempIndex]){
|
||||
tempIndex++;
|
||||
}
|
||||
if(temp < arr[tempIndex]){
|
||||
arr[index] = arr[tempIndex];
|
||||
index = tempIndex;
|
||||
tempIndex = tempIndex * 2 + 1;
|
||||
}else{
|
||||
break;
|
||||
}
|
||||
}
|
||||
arr[index] = temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用递归的方式完成转换大顶堆
|
||||
*/
|
||||
private void transHeap2(int index, int length, int temp){
|
||||
if(index * 2 + 1 > length - 1){
|
||||
return;
|
||||
}
|
||||
|
||||
int tempIndex = index * 2 + 1;
|
||||
if(index * 2 + 2 < length && arr[index * 2 + 2] > arr[index * 2 + 1]){
|
||||
tempIndex = index * 2 + 2;
|
||||
}
|
||||
|
||||
transHeap2(tempIndex, length, temp);
|
||||
|
||||
|
||||
if(arr[index] < arr[tempIndex]){
|
||||
swap(index, tempIndex);
|
||||
}
|
||||
}
|
||||
|
||||
private void swap(int a, int b){
|
||||
int temp = arr[a];
|
||||
arr[a] = arr[b];
|
||||
arr[b] = temp;
|
||||
}
|
||||
|
||||
private void show(){
|
||||
System.out.println("排序后的数组为:");
|
||||
for (int i = 0; i < arr.length; i++) {
|
||||
System.out.print(arr[i] + " ");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] arr = new int[50000];
|
||||
System.out.println("排序前的序列:");
|
||||
for(int i=0; i<50000; i++){
|
||||
arr[i] = (int)(Math.random()*1000000);
|
||||
System.out.print(arr[i] + " ");
|
||||
}
|
||||
HeapSort heapSort = new HeapSort(arr);
|
||||
long startTime = System.currentTimeMillis();
|
||||
heapSort.heapSort();
|
||||
long endTime = System.currentTimeMillis();
|
||||
heapSort.show();
|
||||
System.out.println("排序所花费的时间:" + (endTime - startTime) + "ms");
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user