Javascript experiencing issues with Heapsort

I have been working on implementing heapsort in JavaScript, but I've encountered an issue with an undefined element at position array.length - 2, and the element at index 0 is not sorted. Here is the code snippet:

var heapSort = function(array) {
  var swap = function(array, firstIndex, secondIndex) {
    var temp = array[firstIndex];
    array[firstIndex] = array[secondIndex];
    array[secondIndex] = temp;
  };
  var maxHeap = function(array, i) {
    var l = 2 * i;
    var r = l + 1;
    var largest;
    if (l <= array.heapSize && array[l] > array[i]) {
      largest = l;
    } else {
      largest = i;
    }
    if (r <= array.heapSize && array[r] > array[largest]) {
      largest = r;
    }
    if (largest != i) {
      swap(array, i, largest);
      maxHeap(array, largest);
    }
  };
  var buildHeap = function(array) {
    array.heapSize = array.length;
    for (var i = Math.floor(array.length / 2); i >= 1; i--) {
      maxHeap(array, i);
    }
  };
  buildHeap(array);
  // Code further goes here...
};
var a = [55, 67, 10, 34, 25, 523, 1, -2];
heapSort(a);
document.getElementById("getHeapSort").innerHTML = a;
* {
  font-family: Arial, sans-serif;
}
<p id="getHeapSort"></p>

I observed that the issue arises when array[i] is undefined with i = array.length. I attempted to address this by changing (setting i = array.length - 1), but it resulted in an entirely different output order. Additionally, I noticed that elements at index 0 were never swapped due to the value of i always being greater than 0. Even after attempting to rectify this, the array still ended up in a completely different order.

Answer №1

You were utilizing 1-based indexing instead of the standard 0-based indexing in JavaScript. Additionally, I have included a trace for your convenience.

Give this a try:

var heapSort = function(array) {
  var swap = function(array, firstIndex, secondIndex) {
    var temp = array[firstIndex];
    array[firstIndex] = array[secondIndex];
    array[secondIndex] = temp;
  };
  var maxHeap = function(array, i) {
    var l = 2 * i;
    var r = l + 1;
    var largest;
    if (l < array.heapSize && array[l] > array[i]) {
      largest = l;
    } else {
      largest = i;
    }
    if (r < array.heapSize && array[r] > array[largest]) {
      largest = r;
    }
    if (largest != i) {
      swap(array, i, largest);
      maxHeap(array, largest);
    }
  };
  var buildHeap = function(array) {
    array.heapSize = array.length;
    for (var i = Math.floor(array.length / 2); i >= 0; i--) {
      maxHeap(array, i);
    }
  };
  buildHeap(array);
  for (var i = array.length-1; i >= 1; i--) {
    swap(array, 0, i);
    array.heapSize--;
    maxHeap(array, 0);

    document.getElementById("getHeapSort").innerHTML = document.getElementById("getHeapSort").innerHTML + a + "<br>";
  }
};
var a = [55, 67, 10, 34, 25, 523, 1, -2];
document.getElementById("getHeapSort").innerHTML = a + "<br>";
heapSort(a);

For reference, here is a JFiddle link: http://jsfiddle.net/mbL5enL5/1/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automatically change and submit an <input> value using jQuery

I have been working on a prototype to enable users to access all the data associated with a visualization. The idea is that they would click on a specific point, triggering a modal to appear, and within that modal, a table would dynamically filter based on ...

Is it possible to cache an html page and display it on the current page when reloading?

I have been attempting to design a webpage with links in a table that trigger modals when clicked. These links are added dynamically using Jquery. $("table").append('<tr><td><a href="#exampleModal" data-bs-t ...

Show the input from one HTML form on a different HTML form

Seeking guidance on utilizing local storage in HTML5. How can I extract information from one form and present it on another HTML form page? Picture this: two forms at play here. Upon populating form 1 and hitting the submit button, the content should be v ...

The entire DOM has been seamlessly replaced by React.JS within the Node.js server

I am currently focusing on practicing the MERN structure, so my goal was to start by setting up a node.js server and react front-end. However, I encountered an issue where the entire DOM gets overwritten once the server is fired up. This has left me wonde ...

Issue with Vue.js - Double curly braces not rendering data on the page

I've recently delved into the world of vue.js Strangely enough, the double curly braces syntax doesn't seem to be rendering for me. However, when I utilize the v-text directive, everything falls into place. Here's a snippet of my code: HTM ...

Ajax versus embedding data directly into the HTML code

Currently, my project involves a combination of JavaScript with jQuery and communication with a Django backend. Some aspects of the user interface require Ajax due to the fact that data to be sent is dependent on user input. On the other hand, there is c ...

Switch up the URL and redirect by employing jQuery

Looking for a solution in jQuery to redirect based on user input? <form id="abc"> <input type="text" id="txt" /> </form> If you want to redirect to a URL constructed from the value of the text box, you can try this: var temp = $("#tx ...

The POST function is executed twice, with the first attempt resulting in a failed API call, but the second attempt is

I am experiencing issues with my subscribe dialog, as it seems to be running the API call twice. The first time it fails, but on the second attempt, it succeeds and inserts the email into the database. This double run is causing errors in my AJAX function, ...

Sorting through a collection of subarrays

Within my application, the structure is set up as follows: [ ["section title", [{ item }, { item } ... ]], ["section title", [{ item }, { item } ... ]], ... and so forth When displayed in the view, the sections are placed in panels, with their internal ...

Unable to align span vertically using font-style "Luckiest Guy" in CSS

I have encountered an issue with vertically centering a span using the font-style "Luckiest Guy". https://i.sstatic.net/Lz8o3.png I attempted to use display: flex;align-items: center; on the span, but it did not work. App.vue <template> <div ...

Utilize Protractor Selenium to extract content from a popup window

Having trouble capturing the text from a popup using Protractor with getText? The HTML structure can be found here. This popup only appears for a few seconds before disappearing. Can anyone assist me in retrieving the text from this popup? To retrieve the ...

What is the best way to control the overflow length and display only a specific amount of content at once?

I am currently designing the homepage for a social media platform. I have around 45 dummy posts and I am looking for a way to limit the overflow in CSS so that only 5 posts are displayed at a time. Once the user reaches the bottom of those 5 posts, another ...

Having difficulty accessing a function within the SignalR connection function

I am currently facing an issue while trying to access a specific function within a SignalR connection function. Below is the code snippet showcasing the entire script for better understanding: $(function() { var chat = $.connection.chatHub; chat.c ...

What could be causing my array to be misconverted into JSONP data?

let defaultPosts = new Array([]); defaultPosts[0] = "first post"; defaultPosts[1] = "second post"; defaultPosts[2] = "third post"; The array in the console is showing ["first post", "second post", "third post"]; let jsonString = JSON.stringi ...

Unknown CSS element discovered: bootstrap, gradient, carousel

I recently created a random quote app using javascript, jQuery, and bootstrap on Codepen. Everything worked perfectly there. However, when I organized the files, pushed them to git, and tried to view the app from Safari, I encountered some warnings and t ...

Gaining entry into a JSON object

I'm currently working on a web page that utilizes API data from the Breaking Bad website. I have received this data in JSON format, but I am struggling to figure out how to access only the objects where the "author" is "Walter White." Here is the data ...

Unable to locate the accurate information

Every time I run the cycle, there should be a match with the specified parameters and the message "OK" should appear. However, I am always getting a result of "No". request( { url: 'http://localhost:5000/positions/get', metho ...

Angular.js has encountered an error due to exceeding the maximum call stack size

Hello everyone! I attempted to create recursion in order to extend my $routeProvider in Angular.js with the following code: var pages = { 'home': { 'url': '/', 'partialName': 'index', ...

What is the process for activating an event when a window undergoes a change?

I created a window using the window.open method to display a form. Once the user submits the form, they are redirected to a page called success.html. Is there a way to trigger an event after success.html finishes loading? I attempted the following approach ...

Running a Python Selenium script

I need some help executing this script using selenium. <div class="vbseo_liked"> <a href="http://www.jamiiforums.com/member.php?u=8355" rel="nofollow">Nyaralego</a> , <a href="http://www.jamiiforums.com/member.php?u=8870" rel="nofollo ...