我编写了以下程序来最大化 Java 中的堆。
package heap;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class HeapMaxify
{
public static void main(String[] s)
{
List<Integer> inp = new ArrayList<Integer>();
Scanner inpObj = new Scanner(System.in);
inp.add(inpObj.nextInt());
for(int i=1;i<=inp.get(0);i++)
inp.add(inpObj.nextInt());
System.out.println("Current heap follows :");
int elemInLine = 1;
int count = 0;
for(int i=1;i<=inp.get(0);i++)
{
System.out.print(inp.get(i)+"\t");
count++;
if(count==elemInLine)
{
System.out.println();
count = 0;
elemInLine *= 2;
}
}
maxifyHeap(inp,1);
System.out.println("Maxified heap follows :");
elemInLine = 1;
count = 0;
for(int i=1;i<=inp.get(0);i++)
{
System.out.print(inp.get(i)+"\t");
count++;
if(count==elemInLine)
{
System.out.println();
count = 0;
elemInLine *= 2;
}
}
}
private static void maxifyHeap(List<Integer> inp, int curIndex)
{
int leftIndex = 2*curIndex;
int rightIndex = (2*curIndex)+1;
int largestIndex=0;
int temp;
if(leftIndex<=inp.get(0)&&inp.get(leftIndex)>inp.get(curIndex))
largestIndex = leftIndex;
else
largestIndex = curIndex;
if(rightIndex<=inp.get(0)&&inp.get(rightIndex)>inp.get(largestIndex))
largestIndex = rightIndex;
if(largestIndex!=curIndex)
{
temp = inp.get(largestIndex);
inp.set(largestIndex, inp.get(curIndex));
inp.set(curIndex, temp);
maxifyHeap(inp, largestIndex);
}
}
}
我得到与 inp 相同的输出。我觉得我期望使用递归方法来更改 inp ArrayList 有问题。