# max heap in java 20點

2 個已更新項目:

3 個已更新項目:

ex： 13為左子數，63為node值，52為右子數

### 1 個解答

• 1 0 年前
最佳解答

請參考我的做法

import java.util.*;

public class Y00617 {

private static void createHeap(int[] tmp) {

int[] heap = new int[tmp.length+1];

for(int i = 0; i < heap.length; i++)

heap[i] = -1;

for(int i = 1; i < heap.length; i++) {

heap[i] = tmp[i-1];

int s = i;

int p = i / 2;

while(s >= 2 && heap[p] < heap[s]) {

swap(heap, p, s);

s = p;

p = s / 2;

}

}

for(int i = 1; i < heap.length; i++)

tmp[i-1] = heap[i];

}

private static void swap(int[] number, int i, int j) {

int t;

t = number[i];

number[i] = number[j];

number[j] = t;

}

public static void main(String[] args) {

System.out.print("輸入: ");

Scanner keyin = new Scanner(System.in).useDelimiter("\\D");

ArrayList<Integer> al = new ArrayList<Integer>();

while (keyin.hasNextInt()) {

}

int[] ary = new int[al.size()];

for (int i = 0; i < ary.length; i++) {

ary[i] = al.get(i);

}

createHeap(ary);

System.out.println(Arrays.toString(ary));

}

}