# 一段js的堆排序实现。。

0

function buildMaxHeap( arr ) {
for ( var i = Math.floor( arr.length/2 ) ; i >= 0; i -- ) {
}
}

function heapSort( arr ) {
buildMaxHeap( arr );
for ( var k = arr.length -1 ; k >= 0; k--) {
swap( 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 );
}
}

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() );

Asambojur | 初学一级 | 园豆：192

0

Eric.luo | 园豆：853 (小虾三级) | 2016-09-07 16:44
0
```function buildMaxHeap(arr) {
for (var i = Math.floor(arr.length / 2); i >= 0; i--) {
}
}
function heapSort(arr) {
buildMaxHeap(arr);
for (var k = arr.length - 1; k >= 0; k--) {
swap(0, k);
}
return arr;
}
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);
}
}
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;
}```

您需要登录以后才能回答，未注册用户请先注册