I'm having trouble grasping the concept of Merge Sort in JavaScript

function MergeSortCaller() {
    let array = [7, 2, 9, 3]
    const auxiliaryArray = array.slice();
    partition (array, 0, array.length - 1, auxiliaryArray);
}

function partition(
    mainArray,
    startIdx,
    endIdx,
    auxiliaryArray,
) {
    if (startIdx === endIdx) return;
    const middleIdx = Math.floor((startIdx + endIdx) / 2);
    partition (auxiliaryArray, startIdx, middleIdx, mainArray);
    partition (auxiliaryArray, middleIdx + 1, endIdx, mainArray);
    doMerge (mainArray, startIdx, middleIdx, endIdx, auxiliaryArray);

}

function doMerge(
    mainArray,
    startIdx,
    middleIdx,
    endIdx,
    auxiliaryArray,
) {

    let k = startIdx;
    let i = startIdx;
    let j = middleIdx + 1;
    while (i <= middleIdx && j <= endIdx) {
        if (auxiliaryArray[i] <= auxiliaryArray[j]) {
            mainArray[k++] = auxiliaryArray[i++];
        } else {
            mainArray[k++] = auxiliaryArray[j++];
        }
    }
    while (i <= middleIdx) {
        mainArray[k++] = auxiliaryArray[i++];
    }
    while (j <= endIdx) {
        mainArray[k++] = auxiliaryArray[j++];
    }
    console.log(auxiliaryArray, mainArray)
}

MergeSortCaller()

Output:-

  1. Aux -> 7 2 9 3 Main -> 2 7 9 3

  2. Aux -> 7 2 9 3 Main -> 2 7 3 9

  3. Aux -> 2 7 3 9 Main -> 2 3 7 9

This code is a working implementation of the Merge Sort algorithm. I am puzzled by how in the third call of doMerge(), the auxiliaryArray gets modified even though no changes are made to it directly. All modifications seem to be applied to the mainArray instead. Can someone please explain this to me? Thank you.

Thanks...

Answer №1

https://i.sstatic.net/6ZteF.png

Explore Graphical Structure for an interactive visualization of mergesort that can be beneficial to your understanding.

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

Is it possible to control the visibility of content in HTML based on the current time of day?

Is it possible to display specific parts (divs) on a local site during specific times of the day? If so, how can this be implemented? Thank you. Here is an example of a simple page: <!DOCTYPE html> <html lang="en> <head> <title&g ...

Utilizing variable values in HTML and CSS to enhance a website's functionality

My current project involves modifying an HTML web resource for use in Dynamics 365. I need to replace a static URL with a dynamic value obtained via Javascript, specifically: var URL = Xrm.Page.context.getClientUrl(); There are multiple instances within ...

The error message "Unexpected TypeError: useSearchParams either does not exist as a function or is not iterable in its return value

I'm currently facing a problem with my code, which results in the error message: "Uncaught Error: NextRouter was not mounted" appearing in the console. After some investigation, I discovered that with Next.js version 13 onwards, we should ...

Explore a directory in node.js in alphabetical order in a recursive manner

Is there a method to recursively walk through a directory in alphabetical order? I have been utilizing the node-findit package from https://github.com/substack/node-findit, but it does not provide an alphabetical sorting. Is there a solution that functio ...

The issue of deleting the incorrect document ID in React Firebase

I'm currently facing an issue while trying to implement a delete operation on a Firebase database using Reactjs. The problem lies in my function that seems to be fetching the wrong id from Firebase. There's a button triggering the handleOpen fun ...

Waiting for the completion of the previous observable in an RxJS Interval Observable

I'm trying to create an interval observable that waits for the last execution before proceeding. Here are some attempts I've made: First attempt: interval(1000) .subscribe(async x => { await new Promise(resolve => setTimeout(resolve, ...

Encountering an issue with Meteor and node-celery: "Unable to access property 'slice' of null"

Check out the Github repository for reproducing this issue Run localhost:3000 to replicate the problem. In my setup with Meteor 1.4.4.1, I am utilizing the node-celery npm packages on the server side. Upon Meteor initialization, the client automatically i ...

Prevent unwanted bouncing and zooming on IOS10+ when using routing in VueJS

Currently, I am developing a Vue.js application that integrates with Three.js to display 3D models. I am using Vue.js with Vuetify as the framework and incorporating the Vue.js router. Due to the nature of displaying 3D models, I need to prevent zooming i ...

Is there a more efficient approach to extracting the border width using javascript?

I implemented the following code: const playGard = document.getElementsByClassName("playGard")[0]; const borderW = getComputedStyle(playGard,null).getPropertyValue('border-left-width').substr(0,2); The result I obtained was "10". Is there a m ...

Guide on integrating an HTML and CSS register form in Django

I have successfully created a responsive register and login using HTML and CSS. Instead of utilizing the standard register form and login provided by Django upon configuration, I want to apply my own custom template. To summarize, while I am familiar with ...

How to Align Bootstrap 4 Navbar Brand Logo Separate from Navbar Toggler Button

Can anyone help me with center aligning navbar-brand? When I right align navbar-toggler for mobile devices, it causes the logo to be off-center. Is there a way to independently align these two classes, and if so, how can I achieve this? <nav class="n ...

Utilizing Sequelize's Where clause with the flexibility of optional parameters

Can you guide me on writing Sequelize queries with optional parameters? Consider the below query example: const result : SomeModel[] = await SomeModel.findAll( {where: { id: givenId, ...

Locate the position of a substring within a Uint8Array

I'm working with a Uint8Array that contains the content of a PDF file. My goal is to locate a specific string within this array in order to insert additional content at that particular position. My current approach involves converting the Uint8Array ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

Discovering nodes with changing identification values in polymers automatically

Is there a way to locate a node with a dynamic id value using Polymer's method of finding nodes by id? For instance <template> <div id="{{ id }}"></div> </template> and in JavaScript Polymer("my-element", { ready: f ...

Adjusting iframe height based on content in ReactJS

When tackling this problem in a React environment, the traditional solution falls short due to the dynamic component structure and event model: script: <script> function resizeIframe(obj) { obj.style.height = obj.contentWindow.document.body.s ...

What is the distinction between selecting and entering a date input value?

When a user selects a date, it needs to be immediately sent to the server. If they manually type in the date, it should be sent on blur. The issue arises when the oninput event is triggered for each keydown event, causing unnecessary server requests while ...

I am interested in updating my website's navbar to switch from displaying "login" to "logout" once the user has logged in using

Facing an issue with my navbar logic - I need to switch it from "login" to "logout" when the user is already logged in. Utilizing Nodejs and Ejs templates for this web project, I am currently employing Level 1 Authentication. Initially focusing on the basi ...

What is the reason for the failure of this ajax function when trying to access a specific URL?

Inside index.html, below the body tag: <a href="javascript:setTempInc()">+</a> <a href="javascript:setMode(0)">-</a> And within the <head><script type="text/javascript">: var url = "get_php"; function ajaxRequest() { ...

Argument-based recursive method

Why is the script only printing 'Hello' and not 'Good bye' as well, even though both are passed as arguments on the function call? What could be causing this issue? Note: The script used to work before. It stopped working after adding ...