powrót

Ćwiczenia 11 - Kopiec binarny i Kolejka priorytetowa

Kopiec binarny (1 pkt termin: 13:30:00 07-01-2015)

STRUCT-HEAP
	[]
	length = 100
	heap-size = 0
PARENT(i)
	return i DIV 2
LEFT(i)
	return 2 * i
RIGHT(i)
	return 2 * i + 1
MAX-HEAPIFY(T, i)
	l = LEFT(i)
	r = RIGHT(i)
	if l ≤ T.heap-size AND T[l] > T[i]
		L = l
	else
		L = i
	if r ≤ T.heap-size AND T[r] > T[L]
		L = r
	if L ≠ i
		tmp = T[i]
		T[i] = T[L]
		T[L] = tmp
		MAX-HEAPIFY(T, L)
BUILD-MAX-HEAP(T)
	T.heap-size = T.length
	for i = T.length DIV 2 DOWNTO 1
		MAX-HEAPIFY(T, i)

Kolejka priorytetowa (1 pkt termin: 13:30:00 07-01-2015)

HEAP-MAXIMUM(T)
	return T[1]
HEAP-EXTRACT-MAX(T)
	if T.heap-size < 1
		error "kopiec pusty"
	max = T[1]
	T[1] = T[T.heap-size]
	T.heap-size = T.heap-size - 1
	MAX-HEAPIFY(T,1)
	return max
HEAP-INCREASE-KEY(T,i,key)
	if key < T[i]
		error "klucz mniejszy"
	T[i] = key
	while i > 1 AND T[PARENT(i)] < T[i]
		tmp = T[i]
		T[i] = T[PARENT(i)]
		T[PARENT(i)] = tmp
		i = PARENT(i)
MAX-HEAP-INSERT(T,key)
	T.heap-size = T.heap-size + 1
	T[T.heap-size] = -∞
	HEAP-INCREASE-KEY(T,T.heap-size,key)
  1. MIN HEAPIFY
  2. BUILD MIN HEAP
  3. HEAPSORT (2 pkt termin: 13:30:00 07-01-2015)
  4. usuwanie i-tego elementu
  5. znajdowanie najmniejszego elementu kopca max