Algorithm 替换最小堆中的元素

Algorithm 替换最小堆中的元素,algorithm,data-structures,heap,Algorithm,Data Structures,Heap,这是一个问题。在电话采访中被问到我的朋友 实现一个函数,该函数将把索引i中的元素替换为k,并在最小堆中重新排列堆回 这是我的解决方案,请告诉我是否正确 解决方案1: 1) 堆[i]=k 2) heapify(堆,1) 但在这种情况下,这似乎是错误的: 10 / \ 14 59 (<-was 12 before replacing) .. / \ 55 20 10 / \ 14 59(如果减少键(k)的值小于其父级,则执行MinHeapify(k)在O(logn) 以下

这是一个问题。在电话采访中被问到我的朋友

实现一个函数,该函数将把索引
i
中的元素替换为
k
,并在最小堆中重新排列堆回

这是我的解决方案,请告诉我是否正确

解决方案1:

1) 堆[i]=k
2) heapify(堆,1)

但在这种情况下,这似乎是错误的:

  10
 /  \
14  59 (<-was 12 before replacing)
.. /  \
  55  20
10
/  \

14 59(如果减少键(k)的值小于其父级,则执行MinHeapify(k)

O(logn)

以下操作的伪代码:-

void replaceHeap(int index,int value) {

  heap[index] = value;
  BubbleUp(index);

  Heapify(index);


}

void BubbleUp(int index) {

   parent = index/2;

   while(index>1&&heap[parent]>heap[index]) {

         swapElementAt(parent,index);
         index = parent;
         parent = index/2;
   }

}

Heapify is standard as you have done it

解决方案1可能更好

  • heap[i]=k
  • 如果
    堆[i]
    小于其父级,则将其冒泡(游泳)
  • 否则,如果
    heap[i]
    大于它的一个子项,则将其放入气泡(sink)
运行时间:
O(日志n)

游泳-当它比它的父代小时,与它的父代交换

下沉-当它比它的一个孩子大时,用它最小的孩子交换它

sink
swim
的一些Java代码取自:

private void swim(int k){
而(k>1&小于(k/2,k)){
行政会议(k,k/2);
k=k/2;
}
}
专用空接收器(int k){

(2*k为了简单起见,这里是python中最简单的实现

# Replace item
self.heap[index] = something_new

# Get left child
try:
    left_child = self.heap[2 * index + 1]
except IndexError:
    left_child = None

# Get right child
try:
    right_child = self.heap[2 * index + 2]
except IndexError:
    right_child = None

# Get parent
parent = self.heap[int(math.floor(index / 2))]

# If smaller than parent, swim up
if parent is not None and self.heap[index] < parent:
    swim(index)
    break

# If larger than one of its children sink
if left_child is not None:
    if self.heap[index] > left_child:
        sink(index)
        break

if right_child is not None:
    if self.heap[index] > right_child:
        sink(index)
        break
#更换项目
self.heap[index]=新事物
#离开孩子
尝试:
left_child=self.heap[2*索引+1]
除索引器外:
左\子项=无
#找对孩子
尝试:
right\u child=self.heap[2*索引+2]
除索引器外:
右\子项=无
#得到父母
parent=self.heap[int(math.floor(index/2))]
#如果比父母小,游上来
如果父级不是None且self.heap[index]左\u子级:
水槽(索引)
打破
如果right_child不是None:
如果self.heap[index]>右\u子级:
水槽(索引)
打破

解决方案2是一种可行的方法,依我看。它是有效的,而且非常有效。什么是
递减键(k)
?p=parent(k);while(valid_index(p)和&a[k]