function buildMaxHeap( arr ) {
for ( var i = Math.floor( arr.length/2 ) ; i >= 0; i -- ) {
heapAdjust( arr, i, arr.length );
}
}
function heapSort( arr ) {
buildMaxHeap( arr );
for ( var k = arr.length -1 ; k >= 0; k--) {
swap( 0, k );
heapAdjust( arr, 0, k );
}
return arr;
}
function heapAdjust( arr, index, size ) {
var largest = index;
var left = 2*index + 1 , right = 2*index + 2;
if ( left < size && arr[largest] < arr[left] ) {
largest = left;
}
if ( right < size && arr[largest] < arr[right] ) {
largest = right;
}
if ( largest != index ) {
swap( arr, index, largest );
//heapAdjust( arr, largest, size );
}
}
function swap ( arr, pre, largest ) {
var temp = arr[largest];
arr[largest] = arr[pre];
arr[pre] = temp;
}
console.log( heapSort( [0,9,10,8,7,6,5,4,3,2,1] ).reverse() );请问下我这段堆排序的代码是哪个环节出了问题呢?
得出的数组是1,2,3,4,5,0,7,8,6,9,10
能不能用代码插件排个版,
function buildMaxHeap(arr) { for (var i = Math.floor(arr.length / 2); i >= 0; i--) { heapAdjust(arr, i, arr.length); } } function heapSort(arr) { buildMaxHeap(arr); for (var k = arr.length - 1; k >= 0; k--) { swap(0, k); heapAdjust(arr, 0, k); } return arr; } function heapAdjust(arr, index, size) { var largest = index; var left = 2 * index + 1, right = 2 * index + 2; if (left < size && arr[largest] < arr[left]) { largest = left; } if (right < size && arr[largest] < arr[right]) { largest = right; } if (largest != index) { swap(arr, index, largest); //heapAdjust( arr, largest, size ); } } function swap(arr, pre, largest) { var temp = arr[largest]; arr[largest] = arr[pre]; arr[pre] = temp; } console.log(heapSort([0, 9, 10, 8, 7, 6, 5, 4, 3, 2, 1]).reverse()); //请问下我这段堆排序的代码是哪个环节出了问题呢?得出的数组是1,2,3,4,5,0,7,8,6,9,10
先美化一下,在看问题
swap(0, k);
function swap(arr, pre, largest) { var temp = arr[largest]; arr[largest] = arr[pre]; arr[pre] = temp; }
这块有问题