1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| let arr = [49, 38, 65, 97, 76, 13, 27, 49]; console.log('arr:' + arr); HeapSort(arr); console.log('sortArr:' + arr); function HeapSort(arr){ buildHeap(arr); for(let i=arr.length-1; i>0; i--){ swap(i); headAdjust(arr, 0, i-1); } } function buildHeap(arr){ for(let i=Math.floor(arr.length/2)-1; i>=0; i--){ headAdjust(arr, i, arr.length-1); } } function swap(i){ let swap = arr[i]; arr[i] = arr[0]; arr[0] = swap; }
function headAdjust(arr, i, n){ let current= arr[i]; let child = 2*i+1; while(child <= n){ if(child < n && arr[child] < arr[child + 1]){ child ++; } if(arr[i] < arr[child]){ arr[i] = arr[child]; i= child; child = 2*i + 1; } else{
break; } arr[i] = current; } }
|