Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

Insertion and Deletion in Heaps (การแทรกและลบใน Heap): Binary Heap Operations

วิธี Insert และ Delete ใน Binary Heap สมมติต้นไม้เริ่มต้น:

Insertion and Deletion in Heaps (การแทรกและลบใน Heap): Binary Heap Operations

Insertion Algorithm (อัลกอริทึมแทรก)

insert(heap, n, item):
Begin
    if heap is full then exit
    else
        n := n + 1
        for i := n, i > 1, i := i/2 do
            if item <= heap[i/2] then break
            heap[i] = heap[i/2]
        done
    end if
    heap[i] := item
End

ตัวอย่าง: แทรก 30

Insertion and Deletion in Heaps (การแทรกและลบใน Heap): Binary Heap Operations

Insertion and Deletion in Heaps (การแทรกและลบใน Heap): Binary Heap Operations

Deletion Algorithm (อัลกอริทึมลบ)

delete(heap, n):
Begin
    if heap is empty then exit
    else
        item := heap[1]
        last := heap[n]
        n := n - 1
        for i := 1, j := 2, j <= n, i := j, j := j*2 do
            if j < n then
                if heap[j] < heap[j+1] then j := j+1
            end if
            if last >= heap[j] then break
            heap[i] := heap[j]
        done
    end if
    heap[i] := last
End

ตัวอย่าง: ลบ 30 จาก Heap สุดท้าย

Insertion and Deletion in Heaps (การแทรกและลบใน Heap): Binary Heap Operations