error encountered in quickSort algorithm

function customSort(arr) {
    let pivot = arr[arr.length - 1];
    const rightArr = [];
    const leftArr = [];
    for (let i = 0; i < arr.length - 1 ; i++){
        if (arr[i] > pivot){
            rightArr.push(arr[i]);
        } else {
            leftArr.push(arr[i]);
        }
    }
    if (leftArr.length > 0 && rightArr.length > 0 ){
        return [...customSort(leftArr), pivot , ...customSort(rightArr)];
    } else if (leftArr.length > 0){
        return [...customSort(leftArr), pivot]; 
    } else {
        return [pivot, ...customSort(rightArr)];
    }
}
customSort(arr);

I encountered a "Maximum call stack size exceeded" error. I believe it is related to recursion in the function.

Answer №1

Contained within the quickSort function is the following code:

if (leftArr.length > 0 && rightArr.length > 0 ){
    return [...quickSort(leftArr) , pivot , ...quickSort(rightArr)];
}else if (leftArr.length > 0){
    return [...quickSort(leftArr) , pivot]; 
    
}else {
    return [pivot ,...quickSort(rightArr)];
};

This code block indicates the following:

  • If there are elements both to the left and right, then sort both sides
  • Otherwise, if there are elements only to the left, then sort the left side
  • Otherwise, sort the right side

The issue lies in not accounting for the scenario where both leftArr and rightArr have a length less than or equal to 0. This needs to be handled as well.

The revised code snippet below attempts to address this problem by adding one condition. It may not fully resolve all issues with your initial implementation, but it addresses the logical flaw mentioned above:

//calculate pivot

if (leftArr.length > 0 && rightArr.length > 0 ){
    return [...quickSort(leftArr) , pivot , ...quickSort(rightArr)];
}else if (leftArr.length > 0){
    return [...quickSort(leftArr) , pivot]; 
}else if (rightArr.length > 0){
    return [pivot ,...quickSort(rightArr)];
}else {
    return pivot;
};

A comment is included indicating that calculating the pivot is essential. Various methods can be employed for pivot calculation, as discussed in this article.

Prioritize rectifying the recursive call issue before proceeding further, ensuring the function does not recursively call itself excessively and cause adverse effects on system resources.

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

Vue.js - Difficulty displaying fetched data from API using v-for

My attempt to render a list of data seems to be hitting a roadblock - the data doesn't display when the page loads. The API call works perfectly, fetching all the necessary data and setting it to my data object. Here's the code snippet: once &apo ...

Using Three.js to load an image from a different domain

Despite searching extensively and reading through all available resources, I am unable to find a solution to my issue. I am currently running this code on a local server (IIS). My objective is to load an image from imgur and utilize it as a texture for an ...

Arranging an array by date in Codeigniter

After merging my array, I am facing an issue with sorting them by date because loans and colls have different names for date fields. Here is the code snippet for merging: $loan = $this->db->get('loans')->result_array(); $coll = $this-& ...

Creating a clickable button that will trigger a function when pressed, continuously running the function until the button is released

I am currently working on a project where I am trying to make an object move using an HTML button. However, the function is only executed once with a single click, whereas I want it to execute continuously as long as the button is pressed down. Below is ...

Is it possible to target only those divs within a class that wrap to a new line?

I currently have a series of 7 to 12 divs with the same styling, all floated to the left. Is there a CSS selector that can target the ones flowing onto a second row? I doubt this is achievable with standard CSS, so I'm curious if anyone has any jQuery ...

Guide to attaching data to an AJAX request

I'm new to ajax and recently encountered an issue while working on a project where I needed to send a query from an HTML form. However, I've been unable to send any data for some reason. I tried sending FormData through the xmlhttprequest.send() ...

Unique browsing key

Is there a specific identifier that can uniquely represent the browser you are currently using? I have two applications logged in through ApiGateWay, and I need to determine whether they are both running on the same browser. Therefore, I require a unique ...

After compiling typescript, ES6 Map.forEach is unexpectedly not a function

Exploring the new collection types introduced in ES6 for my TypeScript/React project. interface MyComponentProps{ myMap: Map<String, {isAvailable?: boolean}>, } ... this.props.myMap.keys(); Even though IntelliJ and Webpack compile the code withou ...

In the ajax call, an empty JSON array object is sent as the data

Utilizing JSON data as a parameter for an ajax call: var startDate = dateFormatForSave($("#start_date").val().trim()); var arrayOfStudentsInfo = []; var table = $("#selected_students"); table.find('tr').each(function(i, el) { var rowId = $( ...

Having trouble reaching the upload file in PHP

I am attempting to transfer files to a remote server using JavaScript, with PHP as the backend. The JavaScript code seems to be functioning properly, but on the PHP side, the $_FILES and $_POST arrays are empty. However, the $_SERVER array contains some da ...

Data binding in Vue does not function properly within functional components

Clicking the button will cause the number n to increase, but the UI will display it as constant 1. <script> let n = 1 function add() { console.log(n) return ++n } export default { functional: true, render(h, ctx) { return (<div> ...

Choosing a Query with Puppeteer - Unleashing the Power of Selection in Puppeteer

How do I use Puppeteer to select the html anchor element that clicks and navigates to the Tutorial page? https://i.sstatic.net/6rkNn.png I've tried this but it's not working const puppeteer = require('puppeteer'); const url = process ...

Leveraging jquery's setInterval for automating tasks like a cronjob

I've been experimenting with Cronjobs and I've run into a roadblock. My goal is to have the cronjob execute every X minutes, containing a script with JavaScript that calls an ajax request every second for the next 60 seconds. The ajax call trigge ...

The dynamic data is not displaying on the Chart bundle JavaScript

I am currently utilizing chart bundle js for my project. While everything appears to be functioning properly on alter show, I am encountering an issue with the map display – nothing is showing up as intended. If anyone has a solution to resolve this iss ...

"Angular: Enhancing Functionality with Nested Controllers and Service Dependency Handling

Hey there! I've got a setup with nested angular controllers. The outer one is called personController, while the inner one is personScheduleController. In this arrangement, the person controller reaches out to a service to retrieve person data. On the ...

Hide a div element automatically when all required inputs are filled out, no need for a submit button

Is there a way to hide or close a div automatically after all input fields have been filled out? I'm looking to utilize JavaScript for the task of hiding/closing without needing a submit button. However, I'm unsure how to achieve this. Ideal ...

How can I use jQuery to prevent a click function from running when input fields are left empty

I have step cards with input fields on each card. A "Next" button is provided for each card to change the view. However, I need to prevent the "Next" button from functioning if any input fields on the form are left empty. Below is the code snippet: va ...

Partitions of integers with K elements

In the case of a vector v consisting of F non-negative integers, I am interested in generating all possible sets of K vectors with a size of F each, such that their sum equals v. The matrix C represents these K vectors, with each row summing up to v. For ...

Error message from Meteor-Now deployment: "sh: meteor command not found"

I'm encountering issues deploying my meteor app with meteor-now. I followed a tutorial here, and also attempted deployment using ZEIT's OSX Client, but I keep getting the same error. Is there a workaround that anyone can suggest? Edit 1: H ...

instructions for executing this javascript within the <p> tag

This is the code I have written : <p onload=javascript:alert('sss')>www</p> Unfortunately, the code does not alert 'sss', Can someone please tell me what's wrong with my code? Thank you ...