[Js articles] JS heap sorting

Heap sort is a tree selection sort, implemented by constructing a binary heap. The following is the JavaScript code to implement heap sorting:

function heapSort(arr) {
    
    
  let len = arr.length;
  buildMaxHeap(arr);
  for (let i = len - 1; i > 0; i--) {
    
    
    swap(arr, 0, i);
    len--;
    maxHeapify(arr, 0, len);
  }
  return arr;
}

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

function maxHeapify(arr, i, len) {
    
    
  let l = i * 2 + 1;
  let r = i * 2 + 2;
  let largest = i;
  if (l < len && arr[l] > arr[largest]) {
    
    
    largest = l;
  }
  if (r < len && arr[r] > arr[largest]) {
    
    
    largest = r;
  }
  if (largest != i) {
    
    
    swap(arr, i, largest);
    maxHeapify(arr, largest, len);
  }
}

function swap(arr, i, j) {
    
    
  let temp = arr[i];
  arr[i] = arr[j];
  arr[j] = temp;
}

First, we need to heap the array and build a large top heap. Here, the bottom-up heaping method is adopted from the last non-leaf node (from the node whose subscript is Math.floor(len/2) to 0). Then, we use the swap function to exchange the position of the top element and the tail element of the heap, and reduce the length of the heap. Then, we heap the array again to get a new big top heap. Repeat the above steps until the length of the heap becomes 1, at this time the array is already in order.

Supongo que te gusta

Origin blog.csdn.net/s398511733/article/details/130563105
Recomendado
Clasificación