首页 新闻 会员 周边 捐助

一段js的堆排序实现。。

0
悬赏园豆: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

 

 

Asambojur的主页 Asambojur | 初学一级 | 园豆:192
提问于:2016-09-06 14:11
< >
分享
所有回答(2)
0

能不能用代码插件排个版,

Eric.luo | 园豆:853 (小虾三级) | 2016-09-07 16:44
0
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

先美化一下,在看问题

jgig11 | 园豆:338 (菜鸟二级) | 2016-10-11 09:20

swap(0, k);

function swap(arr, pre, largest) {
    var temp = arr[largest];
    arr[largest] = arr[pre];
    arr[pre] = temp;
}

 

这块有问题

支持(0) 反对(0) jgig11 | 园豆:338 (菜鸟二级) | 2016-10-11 09:22
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册