算法原理
- 首先將數(shù)組構(gòu)建成按照排序方式轉(zhuǎn)換成大頂堆(從小到大)或小頂堆(從大到?。?/li>
- 將堆頂元素和最后一個(gè)元素交換位置,則最后一個(gè)元素為最大值(或最小值)
- 因一出現(xiàn)最大值,所以將長度減小1,再次進(jìn)行前兩步,直至完成
實(shí)現(xiàn)過程說明
- 構(gòu)建大頂堆時(shí),需要找到最后一個(gè)非葉子節(jié)點(diǎn),通過公式array.length/2-1即可找到
- 找到節(jié)點(diǎn)后,對(duì)比他的孩子節(jié)點(diǎn),找到最大的孩子節(jié)點(diǎn)與他替換
代碼實(shí)現(xiàn)
import java.util.Arrays;
public class Heap_Sort {
public static void heapSort(int[] array) {
if (array == null || array.length <= 0) {
return;
}
int temp = 0;
int length = array.length;
for (int i = length / 2 - 1; i >= 0; i--) {
adjustHeap(array, i, length);
}
for (int j = length - 1; j > 0; j--) {
temp = array[0];
array[0] = array[j];
array[j] = temp;
adjustHeap(array, 0, j);
}
}
public static void adjustHeap(int[] array, int i, int length) {
int temp = array[i];
for (int k = i * 2 + 1; k < length; k = k * 2 + 1) {
if (k + 1 < length && array[k] < array[k + 1]) {
k++;
}
if (array[k] > temp) {
array[i] = array[k];
i = k;
} else {
break;
}
}
array[i] = temp;
}
public static void main(String[] args) {
int[] array = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48};
heapSort(array);
System.out.println(Arrays.toString(array));
}
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。