Heapsort - a handy litte class. July 30, 2007 at 9:55 am

Some of you asked me, for some reason, to update an old array-sort-example i´ve rewritten for flash6 in due time - the heapsort. I think it´s not necessary nowadays because flashs built-in array sort-methods are quick and easy to use, but for all those who asked for - here´s a little as3 heapsort class ( download fla and class ).

package fr.utils {
public class heapsort {

var n:int;
var w:int;
var a:Array;

public function heapsort( arr:Array ) {
a = arr;
n = arr.length;
initheap();
}

private function initheap() {
buildheap();
while( n>1 ) {
n–;
exchange(0,n);
downheap(0);
}
}

private function buildheap() {
for (var v:int=n/2-1; v>=0; v–) {
downheap (v);
}
}
private function exchange( i:int, j:int ) {
t=a[i];
a[i]=a[j];
a[j]=t;
}

private function downheap( v:int ) {
w = 2*v + 1;
while ( w
if ( w+1
if ( a[w+1]>a[w] ) w++;
}
if (a[v]>=a[w]) return;
exchange(v, w);
v=w;
w=2*v+1;
}
}
}
}

Leave a Reply