Combining Arrays: combining function that returns multiple indexes starting from index zero in an array

As part of my learning journey, I decided to tackle implementing merge sort in Javascript. The mergeSort(unsortedArray) function is at the core of this implementation, taking an unsorted array and sorting it using the principles of merge sort. Within mergeSort(), there's a call to merge(leftArray, rightArray) which combines two sorted arrays into one sorted array.

The issue seems to lie within the merge() function. When I apply mergeSort to the array:[8,8,7,5,4,6,3,2,1,5,9,8,7,6,5,4,2,3,6,5,4,8] the resulting sorted array comes out as:[1,4,2,3,5,5,9,6,7,8,8]. On investigating, it appears that the problem arises when comparing leftArray[0] and rightArray[0] in the merge() function. Sometimes, instead of just the first index, rightArray[0] returns multiple values like 2,3 and 5,9. This mismatch causes discrepancies in the sorting process. Here's a breakdown of what happens inside merge() during this confusion:

Step1

leftArray:[4,5,6,7,8,8]
rightArray:[1,2,3,5,9]
result: []

Step2

leftArray[4,5,6,7,8,8]
rightArray[2,3,5,9]
result:[1]

Step3

(improper indexing... array[0] is returning two values)
leftArray[0]=4
rightArray[0]=2,3

leftArray[5,6,7,8,8]
rightArray[2,3,5,9]
result[1,4]

Step4

(improper indexing... array[0] is returning two values)
leftArray[0]=5
rightArray[0]=2,3

leftArray[5,6,7,8,8]
rightArray[5,9]
result[1,4,2,3]

...The inconsistency with array[0] resurfaces with rightArray[0] containing 5,9 next. Interestingly, when running merge() separately on leftArray=[4,5,6,7,8,8] and rightArray=[1,2,3,5,9], the result comes out correctly without any anomalies.

//Implement Merge Sort...
    function mergeSort(unsortedArray) {
        var leftArray = [];
        var rightArray = [];
        var result = [];
        
        //Base Case of one element
        if(unsortedArray.length <= 1){
            //alert("Array is size 1 and value: " + unsortedArray);
            return unsortedArray;
        }
        else{
            var halfwayPoint = Math.round(unsortedArray.length/2);
            
            //Sepertate unsortedArray into a left and right array
            for(var i = 0; i < halfwayPoint; i++){
                leftArray.push(unsortedArray[i]);
                //alert("leftArray: "+ leftArray + " index i = " + i);
            }
            for(var i = halfwayPoint; i < unsortedArray.length; i++){
                rightArray.push(unsortedArray[i]);
                //alert("rightArray" + rightArray + " index i = " + i);
            }
            //alert("leftArray: " + leftArray + " rightArray: " + rightArray);
            leftArray = mergeSort(leftArray);
            rightArray = mergeSort(rightArray);
            //alert("Arrays before merge = leftArray: " + leftArray + " rightArray: " + rightArray);
            result = merge(leftArray, rightArray);
            //alert("result: " + result);
        }
        return result;
    }
    
    //Helper function Merge for MergeSort
    function merge(leftArray, rightArray)
    {
        var result = [];
        while(leftArray.length > 0 && rightArray.length > 0){
            //compare first items of both lists
            //alert("top of while loop");
            //alert("leftArray[0] = " + leftArray[0] + " rightArray[0] = " + rightArray[0]);
            if(leftArray[0] >= rightArray[0]){
                result.push(rightArray[0]);
                //alert("result after push rightArray[0] " + result + " and rightArray before splice: "+ rightArray);
                rightArray.splice(0,1);
                //alert("rightArray after splce: " + rightArray);
            }
            else{
                result.push(leftArray[0]);
                //alert("result after push leftArray[0] " + result + " and leftArray before splice: "+ leftArray);
                leftArray.splice(0,1);
                //alert("leftArray after splce: " + leftArray);
            }
        }
        //alert("before leftArray add");
        if(leftArray.length > 0){
            //alert("went into left array > 0 leftArray: " + leftArray);
            result.push(leftArray);
        }
        //alert("before rightArray add");
        if(rightArray.length > 0){
            //alert("went into right array > 0 rightArray: " + rightArray);
            result.push(rightArray);
        }
        //alert("result within merge function: " + result);
        return result;
    }
    //Test Case
    var unsortedArray = [8,8,7,5,4,6,3,2,1,5,9,8,7,6,5,4,2,3,6,5,4,8];
    var sortedArray = mergeSort(unsortedArray);
    lert(sortedArray);
  
    //Problem is when Merge sort has left array and right array described below
    //the merge function will yield proper result on left array and right array
    //if called directly as it is below, however when merge is called through
    //mergeSort with leftArray and rightArray as described below it yields
    // improperResult below
    var leftArray = [4,5,6,7,8,8];
    var rightArray = [1,2,3,5,9];
    var improperResult= [1,4,2,3,5,5,9,6,7,8,8];
    var resultAct = merge(leftArray,rightArray);
    alert(resultAct);
<h1>MergeSort Problem</h1>

Answer №1

It is essential to utilize the Array.prototype.concat() method rather than using .push() in order to concatenate two arrays.

The .concat function merges two or more arrays and returns a new array, whereas push simply appends the target to the end of the array without concatenating arrays.

If you log your original result instead of using alert, you will observe:

[1, 2, 3, 4, 4, Array[2], 5, Array1, Array[2], Array1, Array[2], Array[4]]

This clearly indicates that you have just pushed arrays into the result.

In the following code snippet:

if(leftArray.length > 0){
    result.push(leftArray);
}
if(rightArray.length > 0){
    result.push(rightArray);
}

You should modify it to :

if(leftArray.length > 0){
    result = result.concat(leftArray);
}
if(rightArray.length > 0){
  result = result.concat(rightArray);
}

 Your rewritten content 
<h1>MergeSort Problem</h1>

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

Retrieving the checked value of a checkbox in Angular instead of a boolean value

Currently I am working on a project using ServiceNow and AngularJS. I am having trouble obtaining the value of a checkbox. Here is the code snippet: $scope.userFavourite = function(favourite){ alert(favourite); } <labe for="tea"& ...

Effortlessly upload multiple dynamic files using Nest JS

Attempting to upload files with dynamic keys, however nest.js requires key names. Attempted solution: @UseInterceptors(FilesInterceptor('files')) async uploadFile(@Query() minioDto: MinioDto, @UploadedFiles() files: Array<BufferedFi ...

Stop JQuery from executing when an error is caught

Once the document is ready, I have configured: $.ajaxSetup({ "error": function (XMLHttpRequest, textStatus, errorThrown) { if(XMLHttpRequest.status == 403) { display_modal( 'Please login to continue.', &ap ...

Converting an array to a string with the help of jq

I am working with a json file that includes an array of reasons in the format [] or ["a","b","c"]. My goal is to change drop_reasons=["a","b","c"] in the json to drop_reasons="a,b,c". I ...

Encountering the message "a critical error occurred: 'vips/vips8' file was not located" while using M2 (Apple Silicon) Macs

Encountered a pesky error that read: fatal error: 'vips/vips8' file not found while setting up a React project on my new M2 (Apple Silicon) device. After sifting through multiple reported issues on StackOverflow and github, I pinpointed the culp ...

Angular Unit Testing: Executing Multiple expectGET's within a Singular Test

I am facing an issue with a unit test that fails to read the JSON in the second request properly This is my implementation of the Config factory (function() { 'use strict'; angular.module('commercial.factories').factory(&apos ...

Challenges with displaying TreeTable in SAPUI5

I have a case with a single xml view. Inside this view, there is a treetable with two columns. <core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="sdf_test.App" xmlns:html="http://www.w3.org/1999/xhtml" ...

Firebase Client v9 (npm) experiencing issues with imports

Situation: After finally taking the initiative to update the Firebase library in my app from 9.0.2 compat to the new modular, tree-shakable library, I encountered some issues. Using Windows 10 and WebStorm, my package.json only contains the dependency { " ...

Confirming the order of two columns in JAVA concurrently

Currently, I am utilizing Selenium to extract row data from a table containing two columns and aiming to confirm the correct column order after sorting them in ascending and descending sequences. The code snippet for validating the sorting of a single colu ...

Tips on creating the <th> tag just one time

I have a task that involves dynamically creating cells in a table based on an array of data. However, I am unsure how to also create a header cell for this table within the same function. Is there a way to streamline the process and create the entire table ...

Monitoring VueFire for an empty array attribute

Seeking a resolution to my current issue! I am attempting to integrate Vue.Draggable with VueFire. I have multiple lists with draggable cards that can be moved between them, sorted, duplicated, and more. When the lists have cards populated, Vue.Draggable ...

Easiest method to incorporate dynamic content into a statically generated page using Node.js with Express

Running a static webpage from Node.JS using the Express webserver: app.use('/', express.static('public')); What is the most efficient way to add dynamic content, like a list of items retrieved from a database, to this page? One option ...

Merge various documents in MongoDB and Mongoose into one unified document

As a newcomer to MongoDB and Mongoose, I encountered the following issue: I have a collection with approximately 600 documents in the following format: { _id: ObjectId(<Integer>), sA: [ { age: { value: &l ...

Issues with hover functionality in Javascript, CSS, and HTML

Seeking assistance with my JavaScript, HTML, and CSS development, I ran into an issue while trying to create a hovering function for my webpage. Despite my efforts, the links are not displaying anything when hovered over, and the divs meant for specific ho ...

When text is wrapped within the <li> tag

In this div, the structure is as follows: <div class="box1" id="infobox"> <h2> Point characteristics: </h2> <div style="padding-left:30px" align="left"> <ul> <li class="infobox_list"><b>X value: </b>< ...

Zod handling the visual component

I am currently working on a project using react-file-base64 to handle file metadata such as name, type, size, and base64 encoding. Despite registering zod validation, I encountered an "image required error" even after uploading the image. Upon investigatio ...

The jQuery autocomplete feature is malfunctioning, as it is unable to display any search

Creating a country list within an ajax call involves working with an array of objects: $.ajax({ url: '//maps.googleapis.com/maps/api/geocode/json?address=' + zipCode + '&region=AT', type: 'GET', dataType: &apo ...

What is the best way to assign a value to a PHP array within one single array

I am working with an array and looping through it using a foreach loop. My code looks like this: foreach($array as $a) { echo var_dump($a); } The current output is: How can I adjust my output to look like this: Furthermore, I want ...

Is there a way for the window.onbeforeunload event to wait for an ongoing animation to finish

Exploring the JavaScript code below which utilizes an animation library (such as scriptaculous). window.onbeforeunload = function(event) { document.body.fade(); } When leaving the page, the animation does not finish before the page changes. This raise ...

Interested in gaining knowledge on how to define basic properties on the model within Angular.JS?

As I dive into the demos on the angular.js website, one aspect that caught my attention is the lack of explicit model/properties definition compared to other frameworks like durandal. For instance, how can we access the property "yourName" in a particular ...