演算法-java代碼實現堆排序

來源:互聯網
上載者:User

標籤:label   uil   []   add   code   元素   編寫   main   UI   

 

堆排序 第7節 堆排序練習題 

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

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

測試範例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
 Java (javac 1.7)代碼自動補全     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
}
  您的代碼已儲存
答案正確:恭喜!您提交的程式通過了所有的測試案例

演算法-java代碼實現堆排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.