Javascript Algorithm Array Sort Heap Sort 2
/**//from w w w .jav a2 s. co m * Swap the i-th element with the j-th element of the array a * @param {Array} a the array * @param {Int} i first index * @param {Int} j second index * @return {Array} */ function swap(a,i,j){ var tmp = a[i]; a[i] = a[j]; a[j] = tmp; return a; } /** * Restore the max-heap property on the i-th element * @param {Array} a the array * @param {Int} i index of the element * @param {Int} size size of the heap * @return {Array} */ function maxHeapify(a,i,size){ var l = (2*i)+1; /* left child index */ var r = (2*i)+2; /* right child index */ var largest = i; /* largest element index */ /* check if left child is greater than parent */ if( l<size && a[l]>a[i] ){ largest = l; } /* check if right child is greater than the largest between parent and left child */ if( r<size && a[r]>a[largest] ){ largest = r; } /* swap elements if necessary and call maxHeapify on largest element */ if( i !== largest ){ a = swap(a,i,largest); a = maxHeapify(a,largest,size); } return a; } /** * Given the a array, return a max-heap * @param {Array} a input array * @return {Array} max-heapified array */ function buildMaxHeap(a){ var i = 0; var l = a.length; for( i=Math.floor(l/2); i>=0; i-=1 ){ a = maxHeapify(a,i,l); } return a; } /** * Sort the given array using Heapsort algorithm * @param {Array} a * @return {Array} sorted array */ function heapsort(a){ var i = 0; /* size of the sub-array that is not been "max-heapified" yet; * initially is equal to the array size */ var l = a.length-1; a = buildMaxHeap(a); for( i=l; i>0; i-=1 ){ a = swap(a,0,i); l -=1; a = maxHeapify(a,0,l); } return a; } var arr = [55,13,41,124,-1,0,5]; console.log( heapsort(arr) );