Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def dump(a):
- # print("Array: ",",".join((str(i) for i in a)));
- pass
- swaps=0
- def swap(a,i,j):
- global swaps
- tmp=a[i]; a[i]=a[j]; a[j]=tmp;
- # print("Swap: "+" "*i+"^^ "+" "*(j-i-1)+"^^\n");
- swaps+=1;
- import random
- import time
- sz=1000000; top=sz*10-1
- start=time.time();
- # a=[random.randint(0,top) for i in range(sz)]
- a=[int(random.random()*top) for i in range(sz)]
- # a=[6,5,3,1,8,7,2,4]
- print("Build array: ",time.time()-start)
- dump(a);
- start=time.time();
- # Build the heap
- for i in range(len(a)):
- # dump(a);
- # print("Ins: "+" "*i+"^^")
- x=i;
- j=(i-1)//2;
- while (j>0):
- # print("Cmp: "+" "*j+"^^\n");
- if (a[x]>a[j]): swap(a,j,x); x=j
- j=(j-1)//2
- if (a[x]>a[0]): swap(a,0,x);
- print("--- Heap built (%d swaps) ---"%swaps);
- dump(a);
- top=len(a);
- while (top>1):
- # print("Remove %d from heap"%a[0]);
- top-=1
- swap(a,0,top);
- par=0;
- child=par*2+1;
- while (child<top):
- swapme=par;
- # print("Cmp: "+" "*par+"^^ "+" "*(child-par-1)+"^^ ^^");
- if (a[child]>a[par]): swapme=child;
- if (child<top-1 and a[child+1]>a[swapme]): swapme=child+1;
- if (swapme==par): break; # Parent already greater than both children
- swap(a,par,swapme);
- # dump(a);
- par=swapme;
- child=par*2+1;
- print("--- Array sorted in %d swaps total ---"%swaps);
- print("Total time: ",time.time()-start);
- dump(a);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement