How can we distinguish between the two samples?

Example A:

function mergeAndSort(array){
        if (array.length > 1){
            let middle = parseInt(array.length/2);
            let leftArr = array.slice(0, middle);
            let rightArr = array.slice(middle);
            mergeAndSort(leftArr);
            mergeAndSort(rightArr);  
            return merge(leftArr, rightArr);
        }
        else 
            return array;
    }
    

Example B:

function mergeAndSort(arr){
        if (arr.length > 1){
            let mid = parseInt(arr.length/2);
            let firstHalf = mergeAndSort(arr.slice(0,mid));
            let secondHalf = mergeAndSort(arr.slice(mid));   
            return merge(firstHalf, secondHalf);
        }
        else 
            return arr;
    }
    

Merge function:

function merging(leftArray, rightArray){
        let leftIndex = 0, rightIndex = 0; 
        const mergedResult = [];
        while (leftIndex < leftArray.length && rightIndex < rightArray.length){
            if (leftArray[leftIndex] < rightArray[rightIndex]){
                mergedResult.push(leftArray[leftIndex++]);
            }
            else{
                mergedResult.push(rightArray[rightIndex++]);
            }
        }
        let result = [...mergedResult, ...leftArray.slice(leftIndex), ...rightArray.slice(rightIndex)];
        return result;
    }
    

The output is correct for Example B but not for Example A. Can you identify the key difference between both examples?

let data = [5, 3, 7, 2, 9, 12, 4];
    

Executing Example A on the provided dataset results in [2, 5, 3, 7, 9, 12, 4], which is incorrect.

Answer №1

In order to properly sort the arrays, make sure to update these lines:

left = mergesort(left);
right = mergesort(right);

By making this change, you will avoid working with unsorted arrays.

Answer №2

The code snippet you provided is ineffective because it lacks assigning the result of the mergesort function to a new variable.

To make it work correctly, modify the code as follows:

function mergesort(arr){
    if (arr.length > 1){
        let mid = parseInt(arr.length/2);
        let left = arr.slice(0,mid);
        let right = arr.slice(mid);
        left = mergesort(left);
        right = mergesort(right);  
        return merge(left,right);
    }
    else return arr;
}

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

How can Vue JS be used to assign numbers to specific elements in an array that meet certain conditions?

Imagine having an array of objects within your Vue state like the following: [ {name: "Daniel", default: false}, {name: "Ross", default: true}, {name: "Rachel", default: false}, {name: "Joey", default: false} {n ...

Struggling to resolve the issue while deploying a Next.js application on Netlify. The error seems to be stemming from the import of an image and its

I attempted to eliminate the code on line 4 and line 15 in index.js, then deployed it on Netlify. The functionality is working correctly, but the image is not displaying as desired. However, when I try to modify the code with just lines 4 and 15 included, ...

JavaScript - Calculate the streak of consecutive work days

Consider this array of plans: [ { _id: "1", project_id: "1", day: "2021-03-02" }, { _id: "2", project_id: "1", day: "2021-03-01" }, { _id: "3", project_id: "1", day: "2021-03-03" }, { _id: "4", project_id: "2", day: "2021-03-01" ...

Quoting Properties in Javascript Objects

If we have the object below: var ObjectName = { propertyOne: 1, propertyTwo: 2 } Do we need to include quotes around the object properties like this? var ObjectName = { 'propertyOne': 1, 'propertyTwo': 2 } Is the sol ...

Is there a way to ensure that @angular/core is utilizing the most up-to-date version of zone.js in its peerDependencies configuration?

This code passes the test, but there is an issue: it('should successfully retrieve data when getDownloadProgress() is called', (done: DoneFn) => { let response = { 'process': {}, 'success': 'success ...

Include a parent class within the style tags in your CSS code

Currently, I am facing an issue with a web application that I am developing. On the left side of the page, there is an editable area, and on the right side, there is a live preview. The live preview area contains an HTML file with specific fields that can ...

Validating date inputs with ng-change in AngularJS

I am currently utilizing AngularJS along with AngularJS bootstrap within my webpage. One of the components I have is a date picker directive that is structured like this: <div class="form-group {{dateStatus.class}}"> <p class="input-g ...

Error message in Phaser 3 (Typescript): "The property 'start' is not defined on the 'Scene' type."

I've encountered an issue with switching scenes in Phaser 3. I have attempted to use scene.switch and scene.start, but it seems that these are not recognized methods on the Phaser.Scene object in Phaser 3. How can I go about changing scenes in Phaser ...

Managing an indefinite amount of values within a PHP script

When submitting the data form, there will be a range of 10 to 100 values to be sent to the PHP file. The quantity of inputs is stored in a JavaScript function variable named count, but I am unsure of how to pass this value to the PHP file. One approach I ...

Looking for a speedy solution with a [PHP function] that needs to be converted to a [JavaScript function

Looking for a quick favor - can anyone help me out with this: static function make_url_safe($z){ $z = strtolower($z); $z = preg_replace('/[^a-zA-Z0-9\s] /i', '', $z); $z = str_ireplace(' ', '-', $z) ...

How can you effectively manage Click events within a three.js environment?

I'm working with a world map layer as a plane geometry and I need to handle click events on different parts, such as continents or countries. I want to show popup events on specific parts like information, videos, or image data with links. How can I a ...

Implement a jQuery feature to gradually increase opacity as the user scrolls and the page loads

On a dynamically loaded page via pjax (except in IE), there are several links at the bottom. Whenever one of these hyperlinks is clicked, the page scrolls to the top while still loading. Although I am okay with this behavior, I'm curious if it' ...

In React, the ES6 prototype method map failed to render anything on the screen

Is there an issue with my map method implementation? var App = React.createClass({ getInitialState(){ return { items:[1,2,3] } }, renderItem(){ return( this.state.items.map((item,i))=> <li key={i}> { ...

What is the method for implementing absolute paths rather than relative paths in a React or Next.js project?

In my React project, I frequently use multiple components within various higher-order components. This often leads to long import paths like import MyComponent from '../../../../components/MyComponent'. I am aware that there is a more efficient w ...

Place the input field and submit button side by side horizontally

How can I align my submit button next to the input text in a single row, with the submit button on the right side of the input text? This is my code: <div class="mt-12"> <input id="grid-text" ...

Unable to assign the value of 'innerHTML' to a null property during an AJAX request

I have searched through numerous articles on this site, but I haven't been able to find the solution I'm looking for. Every time I click a cell in my custom div table, I receive the frustrating message "Cannot set property 'innerHTML' ...

Guide for accessing Javascript documentation via console?

There are many times when I am coding in Python, that I find myself wanting to quickly access the documentation for a function. In the iPython console, I can easily do this by entering dir?? which retrieves the documentation for the dir function. Is ther ...

React setState not triggering to close Material-UI dialog

I have implemented my own Material UI dialog component, separate from the provided demos at https://material-ui.com/demos/dialogs/ When I open the dialog, the state changes from false to true. I have included a handleClose function to close the dialog and ...

Struggling to set up a css3 keyframe slide effect and seeking help to properly configure it. Check out the Fiddle for more details

I am looking to create a responsive version of the animation in this fiddle (link provided below). I want the animation to be 100% wide and have a height of 500px. However, when I adjust the width to 100%, it causes issues at the end of the animation. Can ...

Having issues with AngularJS ng-if when implemented within a Form

Is there a way to hide my form after it has been submitted using ng-if? I am facing an issue where clicking the 'See' button toggles the form on and off, but the same functionality does not work with the 'Add' button. Any insights on wh ...