Why isn't the second half of the array being recursively called during binary insertion?

I am attempting to add a number into an already sorted array of unique numbers in such a way that the resulting array remains sorted. The steps I plan to take are as follows:

  1. Divide the array into halves until each half consists of either 1 element or 2 elements
  2. If there are 2 elements: if number falls between the 2 elements, return [element1, number, element2], otherwise return [element1, element2]
  3. If there is 1 element: if number matches element, return [number, element], otherwise return [element]

I believe that a recursive solution should break down the array until number can be added next to its counterpart or inserted between a lower and upper bound. Then the new array is assembled going back up the call stack. (I am aware this approach may not work correctly if number is less than the lowest element or greater than the highest)

This is the code snippet I have written:


function insertNum(num, sortedSet){
    var returnValue;
    console.log(`sortedSet:${sortedSet}`);
    if (sortedSet.length==0){
        return [num];
    }
    if(sortedSet.length>1){
        console.log('length greater than 1');
        output = splitInHalf(sortedSet);
        if(num>output.first[output.first.length-1]&&num<output.second[0]){
            console.log(`${num} belongs between`);
            return output.first.concat([num]).concat(output.second);
        }
        else{
            return insertNum(num, output.first).concat(insertNum(num, output.second));
        }
    }
    else{
        if(num == sortedSet[0]){
            returnValue = [num, sortedSet[0]];
            console.log(`returning append:${returnValue}`);
            return returnValue;
        }
        else{
            return sortedSet;
        }
    }
}

function splitInHalf(sortedSet){
    halflength_floor = Math.floor(sortedSet.length/2);
    halflength_ceil = Math.ceil(sortedSet.length/2);
    console.log(`halflength_floor:${halflength_floor}`);
    console.log(`halflength_ceil:${halflength_ceil}`);
    first = sortedSet.slice(0, halflength_floor);
    second = sortedSet.slice(halflength_floor);
    console.log(`first:${first}`);
    console.log(`second:${second}`);
    var output = [];
    output.first = first;
    output.second = second;
    return output;
}

console.log(insertNum(7, [2,3,5,6,8]));

The current output obtained is:


sortedSet: 2, 3, 5, 6, 8
length greater than 1
halflength_floor: 2
halflength_ceil: 3
first: 2, 3
second: 5, 6, 8
sortedSet: 2, 3
length greater than 1
halflength_floor: 1
halflength_ceil: 1
first: 2
second: 3
sortedSet: 2
sortedSet: 3
sortedSet: 3
[ 2, 3, 3 ]

The issue arises because the following outputs are never observed:


sortedSet: 5
sortedSet: 6, 8

This leads me to suspect that in the initial invocation of:


insertNum(num, first).concat(insertNum(num, second))

where the arguments should be:


insertNum(7, [2, 3]).concat(insertNum(7, [5, 6, 8])

only the first insertNum() call is executing, while the other insertNum() within concat() does not trigger. Why is this happening?

Answer №1

Kindly modify the code as follows:

Instead of

output=splitInHalf(sortedSet);

Use this:

var output=splitInHalf(sortedSet);

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

Not all dynamic content is loaded through Ajax requests on a single domain

I currently have my domain forwarded (cloaked) to The main page (index.html) utilizes Ajax for loading content. All content loads properly at the original host (moppy.co.uk/wtcdi). However, on the forwarded domain (whatthecatdragged.in), some content fai ...

What is the threading model utilized by node.js?

Upon establishing a connection with a server operating on node.js, how is the connection handled? Is it one connection per process? Does it follow a connection per thread model? Or does it operate based on request per thread? Alternatively, does it use ...

How to utilize Node.js to pause execution and wait for a specific function to

In my coding scenario, I am dealing with a specific code snippet that is part of a larger if statement block: message.reply({ embeds: [multipleUsersEmbedFunction("Multiple Users Found", `The following users were found:\n${string}`, members)] ...

What is the best way to authenticate a SOAP Request?

Is there a quick method to validate SOAP messages efficiently? I have come across validators for JSON objects, but is there anything similar for SOAP? I keep receiving a 'Bad Request: 400' error response with an AJAX post I am trying to implement ...

Can ng-packagr create scripts that are compatible with running in a web browser like regular JavaScript?

Is it feasible to utilize ng-packagr to compile a library into a single script file that can be executed on a web browser by importing it as <script src="bundle.js"></script>? For instance, if I have a main.ts file that contains cons ...

Is there a way to identify if you are at the bottom row of a column defined by CSS styling?

I have implemented the new CSS-style column to divide a single unordered list into multiple columns. Now, I am trying to figure out how to target the last element in each column using JavaScript or CSS. Here is my HTML: <ul> <li /> <li ...

Leveraging JavascriptExecutor for typing and clicking on a specific web element

My goal is to open a link in a new tab and switch to that tab using Selenium in Java with a Firefox browser. I have been successful in opening the link in the same window but am struggling to incorporate sendKeys for my desired action. WebElement we = dri ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

extract non-alphanumeric characters from an array of strings using javascript

I am trying to loop over an array of strings in JavaScript and remove special characters from elements that contain them. I have been successful in achieving this with individual strings, but I am facing some challenges when working with arrays of string ...

The error message "TypeError: res.json is not a function in express.router" indicates that

I encountered the following error message and I'm not sure how to resolve it: TypeError: res.json is not a function I have reviewed the express documentation but couldn't find any syntax errors or issues. Here is my code: index.js import expr ...

Setting the default radio button selection in Angular 2

Present within my interface are two radio buttons, not dynamically produced: <input type="radio" name="orderbydescending" [(ngModel)]="orderbydescending" [value]="['+recordStartDate']">Ascending<br> <input type="radio" name="order ...

Issues with IE7 related to Jquery and potentially HTML as well

I am currently working on a website project for a local charity organization, and I am encountering technical issues with compatibility in IE7. The website functions perfectly in all other browsers I have tested, and it even passes the validation process o ...

The chronicles of UIButton Press record in the annals

Currently, I have a dynamic array of buttons generated on the screen, which is functioning perfectly. However, I am facing an issue with storing a history of the pressed buttons. On each button touch up event, a -(void)onTouch function is called to perform ...

Combine several dictionary values under a single dictionary key in JavaScript

I have a unique dictionary structure displayed below. My goal is to populate it with values in a specific way. It all begins here var animals = { flying : {}, underground : {}, aquatic : {}, desert : {} }; To illustrat ...

Is there a way to prevent camera motion in three.js when the escape key and directional keys are activated?

While working on my project with Pointer Lock Controls, I came across a bug. When the player is pressing any directional keys on the keyboard and simultaneously presses the escape button to turn off the Pointer Lock Controls, the camera continues to move ...

The 'errorReason' property is not found within the 'MessageWithMdEnforced' type

I am currently working on a project using meteor, react, and typescript. Here is the section of code that is causing an error: {message?.errorReason && <div>{message?.errorReason}</div> } The error message I am encountering is: "P ...

Script to automatically open a PDF document immediately after it has been generated

Can Apps Script in Google Sheets automatically open a PDF file right after it's created? I have a script that generates a PDF from a Google Sheet and saves it on Google Drive. Is there a way for the script to also open the PDF so it can be easily pri ...

Guide to retrieving a user's current address in JSON format using Google API Key integrated into a CDN link

Setting the user's current location on my website has been a challenge. Using Java Script to obtain the geographical coordinates (longitude and latitude) was successful, but converting them into an address format proved tricky. My solution involved le ...

Why is My JQuery Button Data Null?

I am facing an issue with a button where I want to pass the HTML object as a parameter to a JavaScript function. The objective is to print the data-hi attribute value from the element in the button. HTML BUTTON <button type = "button" onclick = "whoIs ...

Utilize JavaScript for labeling purposes

Currently, I am working on a WebGL project that involves plotting lines across the globe using three.js. While the plotting itself is functioning correctly, I am facing difficulties in labeling the points from where the plot starts and ends. If anyone coul ...