Heapsort

Strom

Reprezentace

Halda a binární halda

Halda

Binární halda

Reprezentace v poli

Vybudování haldy

Heapify

Funkce Heapify(A,i)

function Heapify(A,i)
    largest = i
    if Left(i) <= A.size and A[left(i)] > A[i] then
        largest = Left(i)
    if Rigth(i) <= A.size and A[Right(i)] > A[largest] then
        largest = Right(i)
    if largest != i then
        Swap(A[i],A[largest])
        Heapify(A,lagest)
function BuildHeap(A)
    A.size = len(A)
    for i = A.size // 2 downto 0 do
        Heapify(A,i)

Algoritmus řazení haldou, Heapsort

algorithm HeapSort(A)
    BuildHeap(A)
    for i = len(A) downto 1 do
        Swap(A[i],A[0])
        A.size -= 1
        Heapify(A,0)

složitost

Prioritní fronta

Maximum

function Maximum(A)
    return A[0]

ExtractMax

function ExtractMax(A)
    if A.size == 0 then
        return None
    max = A[0]
    A[0] = A[A.size-1]
    A.size -= 1
    Heapify(A,0)
    return max

IncreaseKey

function IncreaseKey(A,i,key)
    A[i] = key
    while i > 0 and A[Parent(i)] < A[i] do
        Swap(A[i],A[Parent(i)])
        i = Parent(i)

Insert

function Insert(A,key)
    A.size += 1
    A[A.size] = $-\infty$
    IncreaseKey(A,A.size,key)

Řazení v lineráním čase

Counting sort - řazení počítáním

algorithm CountingSort(A,B,k)
    for i = 0 to k do
        C[i] = 0
    for j = 0 to len(A) - 1 do
        C[A[j]] += 1
    for i = 1 to k do
        C[i] += C[i-1]
    for j = len(A)-1 downto 0 do
        B[C[A[j]]-1] = A[j]
        C[A[j]] -= 1

Radix sort - číslicové řazení

algorithm RadixSort(A,d)
    for i = 1 to d do
        použij stabilní řazení a seřaď položky podle i-te číslice

Časová složitost

Binární čísla

Bucket sort - přihrádkové řazení