자바·파이썬·자바스크립트/파이썬 프로그래밍

힙정렬에서 downheap을 써서 heapify를 하는 이유

바로이순간 2011. 12. 6. 17:42

# python3 version

import random, time

def makelist(m,n):

    al=[]

    for x in range(n):

        al.append(random.randint(1,m))

    return al

def downheap(h,i):

    n=len(h)

    v=h[i]

    while i<n//2:

        ix=i+i+1

        if ix<n-1 and h[ix]<h[ix+1]: 

            ix=ix+1

        if v>h[ix]: break 

        h[i]=h[ix]

        i=ix

    h[i]=v

def downheapOne(h,n):

    i=0

    v=h[i]

    while i<n//2:

        ix=i+i+1

        if ix<n-1 and h[ix]<h[ix+1]: 

            ix=ix+1

        if v>h[ix]: break 

        h[i]=h[ix]

        i=ix

    h[i]=v

def upheap(h, k):

    h.append(k)

    i=len(h)-1

    ip=(i-1)//2

    v=h[i]

    while i>0 and v>h[ip]:

        h[i]=h[ip]

        i,ip=ip,(ip-1)//2

    h[i]=v

def upheapOne(h, i):

    ip=(i-1)//2

    v=h[i]

    while i>0 and v>h[ip]:

        h[i]=h[ip]

        i,ip=ip,(ip-1)//2

    h[i]=v

def heapify(h):

    i=len(h)//2-1

    while i>=0:

        downheap(h,i)

        i=i-1

def heapifyup(h):

    n=len(h)

    for i in range(1,n):

        upheapOne(h,i)

def compare(n):

    al=makelist(1000000000,n)

    bl=al[:]

    t1s=time.time()

    heapify(al)

    t1e=time.time()

    t2s=time.time()

    heapifyup(bl)

    t2e=time.time()

    print('downheap:',t1e-t1s,'upheap:',t2e-t2s)

def heapsort(h):

    n=len(h)

    heapify(h)

    for x in range(n-1,0,-1):

        h[0],h[x]=h[x],h[0]

        downheapOne(h,x)

n=int(input('Enter number:'))

compare(n)

#n=int(input('Enter number:'))
#al=makelist(1000,n)
#print('***',al)
#heapsort(al)
#print('###',al)