From 6036289d175374bec16b5ef6ecdd7bf9a198b696 Mon Sep 17 00:00:00 2001 From: liangjinglin Date: Tue, 21 Jan 2025 21:19:17 +0800 Subject: [PATCH] =?UTF-8?q?2025-01-21=20=E5=A0=86=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/dataANDcalc/java/tree/HeapSort.java | 108 ++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 src/dataANDcalc/java/tree/HeapSort.java diff --git a/src/dataANDcalc/java/tree/HeapSort.java b/src/dataANDcalc/java/tree/HeapSort.java new file mode 100644 index 0000000..1b3825c --- /dev/null +++ b/src/dataANDcalc/java/tree/HeapSort.java @@ -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"); + } +}