Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

heap - HeapSort implementation in Javascript

I am learning about heaps and I wanted to implement the heap sort algorithm in Javascript using MinHeap. The issue is that I keep getting a non-sorted array. I even tried to just translate a working algorithm from C++ to Javascript. Orginal algorithm link: https://www.geeksforgeeks.org/heap-sort-for-decreasing-order-using-min-heap/

C++:

// To heapify a subtree rooted with node i which is 
// an index in arr[]. n is size of heap 
void heapify(int arr[], int n, int i) 
{ 
    int smallest = i; // Initialize smalles as root 
    int l = 2 * i + 1; // left = 2*i + 1 
    int r = 2 * i + 2; // right = 2*i + 2 


// If left child is smaller than root 
if (l < n && arr[l] < arr[smallest]) 
    smallest = l; 

// If right child is smaller than smallest so far 
if (r < n && arr[r] < arr[smallest]) 
    smallest = r; 

// If smallest is not root 
if (smallest != i) { 
    swap(arr[i], arr[smallest]); 

    // Recursively heapify the affected sub-tree 
    heapify(arr, n, smallest); 


 } 
} 



// main function to do heap sort 
void heapSort(int arr[], int n) 
{ 
    // Build heap (rearrange array) 
    for (int i = n / 2 - 1; i >= 0; i--) 
        heapify(arr, n, i); 
  
    // One by one extract an element from heap 
    for (int i = n - 1; i >= 0; i--) { 
        // Move current root to end 
        swap(arr[0], arr[i]); 
  
        // call max heapify on the reduced heap 
        heapify(arr, i, 0); 
    } 
} 

Javascipt (translated code):

    function swap(arr, i, j){
    const c = arr[i];
    arr[i] = arr[j];
    arr[j] = c;
}

function heapify(arr, n, i) 
{ 
    let smallest = i; // Initialize smalles as root 
    let l = 2 * i + 1; // left = 2*i + 1 
    let r = 2 * i + 2; // right = 2*i + 2 
  
    // If left child is smaller than root 
    if (l < n && arr[l] < arr[smallest]) 
        smallest = l; 
  
    // If right child is smaller than smallest so far 
    if (r < n && arr[r] < arr[smallest]) 
        smallest = r; 
  
    // If smallest is not root 
    if (smallest != i) { 
        swap(arr[i], arr[smallest]); 
  
        // Recursively heapify the affected sub-tree 
        heapify(arr, n, smallest); 
    } 
} 
  
// main function to do heap sort 
function heapSort(arr, n) 
{ 
    // Build heap (rearrange array) 
    for (let i = n / 2 - 1; i >= 0; i--) 
        heapify(arr, n, i); 
  
    // One by one extract an element from heap 
    for (let i = n - 1; i >= 0; i--) { 
        // Move current root to end 
        swap(arr[0], arr[i]); 
  
        // call max heapify on the reduced heap 
        heapify(arr, i, 0); 
    } 
} 

when I try with this array arr = [1,2,7,3,5], the heapSort algorithm returns this table [ 1, 2, 7, 3, 5 ];

Can you please help me figure out what's wrong with the JS implementation? thank you in advance!

question from:https://stackoverflow.com/questions/65644699/heapsort-implementation-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This code should go fine:

const heapify = (arr, length, i) => {
  let largest = i
  const left = i * 2 + 1
  const right = left + 1

  if (left < length && arr[left] > arr[largest]) {
    largest = left
  }

  if (right < length && arr[right] > arr[largest]) {
    largest = right
  }

  if (largest !== i) {
    [arr[i], arr[largest]] = [arr[largest], arr[i]]
    heapify(arr, length, largest)
  }

  return arr
}

const heapSort = arr => {
  const length = arr.length
  let i = Math.floor(length / 2 - 1)
  let k = length - 1

  while (i >= 0) {
    heapify(arr, length, i)
    i--
  }

  while (k >= 0) {
    [arr[0], arr[k]] = [arr[k], arr[0]]
    heapify(arr, k, 0)
    k--
  }

  return arr
}

const arr = [4, 6, 3, 2, 9];
sortedArr = heapSort(arr);

console.log("Sorted array is 
", sortedArr)

I took it from here. Take a look at the post if you are more interested in how it's implemented. It's very well explained.

UPDATE

Ok so, about your code, I see exactly 2 problems:

  1. You are incorrectly using the "swap" function. Just change swap(arr[i], arr[smallest] by swap(arr, i, smallest); and swap(arr[0], arr[i]) by swap(arr, 0, i). Also, if you want to use the latest ES6 features you can swap elements in an array without implementing that "swap" function, just like this: [arr[0], arr[2]] = [arr[2], arr[0]] (this will swap the element at position 0 with the element at position 2). This is called destructuring assignment.
  2. In the first for loop in your "heapSort" function, initialize i variable to an integer (notice that n / 2 could be a float). You can do it like this: let i = Math.floor(n / 2 - 1).

Here I leave you the fixed code. I've executed it by myself and it works:

function swap(arr, i, j){
  const c = arr[i];
  arr[i] = arr[j];
  arr[j] = c;
}

function heapify(arr, n, i) 
{ 
  let smallest = i; // Initialize smallest as root 
  let l = 2 * i + 1; // left = 2*i + 1 
  let r = 2 * i + 2; // right = 2*i + 2 

  // If left child is smaller than root 
  if (l < n && arr[l] < arr[smallest]) 
      smallest = l; 

  // If right child is smaller than smallest so far 
  if (r < n && arr[r] < arr[smallest]) 
      smallest = r; 

  // If smallest is not root 
  if (smallest != i) { 
      swap(arr, i, smallest); 

      // Recursively heapify the affected sub-tree 
      heapify(arr, n, smallest); 
  } 
} 

// main function to do heap sort 
function heapSort(arr, n) 
{ 
  // Build heap (rearrange array) 
  for (let i = Math.floor(n / 2 - 1); i >= 0; i--) 
      heapify(arr, n, i); 

  // One by one extract an element from heap 
  for (let i = n - 1; i >= 0; i--) { 
      // Move current root to end 
      swap(arr, 0, i); 

      // call max heapify on the reduced heap 
      heapify(arr, i, 0); 
  } 
}

const arr = [4, 6, 3, 2, 9];
heapSort(arr, arr.length);

console.log("Sorted array is 
", arr)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...