mramine364

heap Sort

May 20th, 2016
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function heapSort(t){
  2.     _buildHeap(t);
  3.     var len = t.length-2;
  4.     while(len>=1){
  5.         _heapSwap2(t, 0, len);
  6.         temp = t[0];
  7.         t[0] = t[len];
  8.         t[len] = temp;
  9.         len--;
  10.     }
  11. }
  12. function _heapSwap2(t, i, l){
  13.     var i1 = 2*i+1, i2 =2*i+2, maxi;
  14.     if( i2>l ){
  15.         if( i1>l )
  16.             return;
  17.         else
  18.             maxi = i1;    
  19.     }else{
  20.         if( t[i1]<t[i2] )
  21.             maxi = i2;
  22.         else
  23.             maxi = i1;
  24.     }  
  25.     if( t[i]<t[maxi] ){
  26.         var temp = t[i];
  27.         t[i] = t[maxi];
  28.         t[maxi] = temp;
  29.         _heapSwap2(t, maxi, l);
  30.     }
  31. }
  32. function _heapSwap(t, i){
  33.     while( i!=0 ){
  34.         j = Math.ceil(i/2)-1;
  35.         if( t[j]<t[i] ){
  36.             var temp = t[i];
  37.             t[i] = t[j];
  38.             t[j] = temp;
  39.             i = j;
  40.         }else
  41.             i=0;
  42.     }
  43. }
  44. function _buildHeap(t){
  45.     len = t.length;
  46.     i = 0;
  47.     while( i<len ){
  48.         _heapSwap(t, i);
  49.         i++;
  50.     }
  51.     var temp = t[0];
  52.     t[0] = t[len-1];
  53.     t[len-1] = temp;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment