算法-java代碼實現堆排序


 


堆排序

 

第7節 堆排序練習題

 

對於一個int數組,請編寫一個堆排序算法,對數組元素排序。

給定一個int數組A及數組的大小n,請返回排序后的數組。

測試樣例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
 
 
 
1
import java.util.*;
2
 
                       
3
public class HeapSort {
4
    public int[] heapSort(int[] A, int n) {
5
        int lastIndex = n - 1;
6
        buildMaxHeap(A, lastIndex);//建立最大堆
7
        while(lastIndex > 0){
8
            swap(A, 0, lastIndex);
9
            if(--lastIndex == 0)//只剩一個元素,就不用調整堆了,排序結束
10
                break;
11
            adjustHeap(A,0,lastIndex);    
12
        }
13
        return A;
14
    }
15
 
                       
16
    public void buildMaxHeap(int[] arr, int lastIndex) {
17
        // 從最后一個元素的父節點開始進行調整,一直調整到根節點結束
18
        int j = (lastIndex - 1) / 2;
19
        while (j >= 0) {
20
            int rootIndex = j;
21
            adjustHeap(arr, rootIndex, lastIndex);
22
            j--;
23
        }
24
    }
25
 
                       
26
    public void adjustHeap(int[] arr, int rootIndex, int lastIndex) {//從根節點開始往下調整
27
        int biggerIndex = rootIndex;
28
        int leftChildIndex = rootIndex * 2 + 1; 
29
        int rightChildIndex = rootIndex * 2 + 2;
30
 
                       
31
        if(rightChildIndex <= lastIndex){//如果右孩子存在,則左孩子一定存在
32
            if(arr[rightChildIndex] > arr[rootIndex] || arr[leftChildIndex] > arr[rootIndex]){
33
                //將子節點更大的元素下標賦值給biggerIndex
34
                biggerIndex = arr[rightChildIndex] > arr[leftChildIndex]?rightChildIndex:leftChildIndex;
35
            }
36
        }
37
        else if(leftChildIndex <= lastIndex){//保證左孩子存在,且不能越界
38
            if(arr[leftChildIndex] > arr[rootIndex]){
39
                biggerIndex = leftChildIndex;
40
            }
41
        }
42
        if(biggerIndex != rootIndex){
43
            swap(arr, biggerIndex, rootIndex);
44
            adjustHeap(arr, biggerIndex, lastIndex);
45
        }
46
 
                       
47
    }
48
 
                       
49
    public void swap(int[] arr, int biggerIndex, int rootIndex) {
50
        int temp = arr[rootIndex];
51
        arr[rootIndex] = arr[biggerIndex];
52
        arr[biggerIndex] = temp;
53
    }
54
}
 
 
您的代碼已保存
答案正確:恭喜!您提交的程序通過了所有的測試用例


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM