如何在Java中用Heap编写bubbleDown方法?
我知道有几个像这样的问题贴满了堆栈溢出,但是没有一个真正回答我的问题。我正在编写一个助手私有bubbleDown方法来帮助我在公共静态HeapSort方法上排序 我知道这个想法是将a本身视为最大堆,其数据从0开始(而不是1)如何在Java中用Heap编写bubbleDown方法?,java,heap,priority-queue,bubble-sort,heapsort,Java,Heap,Priority Queue,Bubble Sort,Heapsort,我知道有几个像这样的问题贴满了堆栈溢出,但是没有一个真正回答我的问题。我正在编写一个助手私有bubbleDown方法来帮助我在公共静态HeapSort方法上排序 我知道这个想法是将a本身视为最大堆,其数据从0开始(而不是1) a实际上不是按堆顺序排列的 但是,如果您从最后一个非叶节点开始,反复“冒泡”每个非叶节点,您最终将拥有一个适当的堆 我已经写了这个算法,但是我不确定这是否确实有效 public class MaxHeapPriorityQueue<E extends Compar
- a实际上不是按堆顺序排列的
- 但是,如果您从最后一个非叶节点开始,反复“冒泡”每个非叶节点,您最终将拥有一个适当的堆
public class MaxHeapPriorityQueue<E extends Comparable<E>>
{
private E[] elementData;
private int size;
@SuppressWarnings("unchecked")
public MaxHeapPriorityQueue()
{
elementData = (E[]) new Comparable[10];
size = 0;
}
public static void heapSort(Comparable[] a, int size)
{
MaxHeapPriorityQueue mhpq = new MaxHeapPriorityQueue();
mhpq.elementData = a;
mhpq.size = size;
for (Comparable n : a)
{
mhpq.bubbleDown((int) n);
}
for (int i = 0; i < a.length-1; i++)
{
a[i] = mhpq.sortRemove();
}
}
private void bubbleDown(int index)
{
boolean found = false;
while(!found)
{
int leftIndex = lChild(index);
int rightIndex = rightChild(index);
int largestChildIndex = leftIndex;
if(hasRChild(index))
{
if(elementData[leftIndex].compareTo(elementData[rightIndex]) < 0 )
{
largestChildIndex = rightIndex;
}
}
if(hasLChild(index))
{
if(elementData[largestChildIndex].compareTo(elementData[index]) > 0)
{
swap(elementData, largestChildIndex , index);
index = largestChildIndex;
}
else
{
found = true;
}
}
else //Probably a leaf
{
found = true;
}
}
}
公共类MaxHeapPriorityQueue
{
私有E[]元素数据;
私有整数大小;
@抑制警告(“未选中”)
public MaxHeapPriorityQueue()
{
elementData=(E[])新可比[10];
尺寸=0;
}
公共静态空堆堆(可比[]a,整数大小)
{
MaxHeapPriorityQueue mhpq=新的MaxHeapPriorityQueue();
mhpq.elementData=a;
mhpq.size=尺寸;
适用于(可比n:a)
{
mhpq.bubbleDown((int)n);
}
for(int i=0;i0
{
交换(elementData、largestChildIndex、index);
指数=最大儿童指数;
}
其他的
{
发现=真;
}
}
否则//可能是一片叶子
{
发现=真;
}
}
}
现在一切似乎都运行得更平稳了,只是当我有重复的值时,它们的顺序不正确。我在冒泡方法中找不到这个错误。以下是我得到的结果
private void bubbleDown(int index)
{
boolean found = false;
while(!found && (2*index +1) < size)
{
int left = leftChild(index) + 1;
int right = rightChild(index) + 1;
int child = left;
if((index*2 +2) < size && elementData[right].compareTo(elementData[left]) > 0)
{
child = right;
}
if(elementData[index].compareTo(elementData[child]) < 0)
{
swap(elementData, index, child);
index = child;
}
else
{
found = true;
}
}
}
private void bubbleDown(int索引)
{
布尔值=false;
而(!found&(2*index+1)0
{
儿童=权利;
}
if(elementData[index].compareTo(elementData[child])<0
{
交换(元素数据、索引、子级);
指数=儿童;
}
其他的
{
发现=真;
}
}
}
这个问题还与我之前提出的另外两个问题联系在一起