I am struggling to grasp the flow of this code execution

Hi there, I just started my journey in JavaScript learning about two weeks ago. I would really appreciate it if someone could walk me through the execution steps of the code provided below.

function sort(nums) {
  function minIndex(left, right) {
    if (right === nums.length) {
      return left;
    } else if (nums[right] < nums[left]) {
      return minIndex(right, right + 1);
    } else {
      return minIndex(left, right + 1);
    }
  }

  for (let i = 0; i < nums.length; i++) {
    let selected = minIndex(i, i + 1);
    if (i !== selected) {
      let tmp = nums[i];
      nums[i] = nums[selected];
      nums[selected] = tmp;
    }
  }
}

let nums = [10, 3, 5, 2, 4];
sort(nums);
console.log(nums);

Answer №1

Make sure to label each step from 1 to 11.

Take note of the loops and recursive calls within the code. It's recommended to familiarize yourself with recursion before delving into this code for a better understanding.

An additional note: I have included logging for each instance the minIndex function is invoked, displaying the current indices and values being compared.

function sort(nums) {
  function minIndex(left, right) {
    const condition1 = right === nums.length;
    const condition2 = !condition1 && nums[right] < nums[left>;
    
    console.log(JSON.stringify({
      condition: condition1 ? 1 : condition2 ? 2 : 3,
      left: left,
      right: right,
      expression: condition1 ?
        'DONE' : `${nums[right]} < ${nums[left]} = ${condition2}`
    }))
    
    if (condition1) {                      // 5a. condition
      return left;                         // 6a. return?
    } else if (condition2) {               // 5b. condition
      return minIndex(right, right + 1);   // 6b. recursion, go back to 5a
    } else {                               // 5c. condition
      return minIndex(left, right + 1);    // 6c. recursion, go back to 5a
    }
  }

  for (let i = 0; i < nums.length; i++) {  // 3. start loop
    console.log(`LOOP: ${i + 1}/${nums.length}`);
    let selected = minIndex(i, i + 1);     // 4. find
    if (i !== selected) {                  // 7. conditional
      let tmp = nums[i];                   // 8. begin swap
      nums[i] = nums[selected];            // 9. swap
      nums[selected] = tmp;                // 10. complete swap, go back to 3
    }
  }
}

let nums = [10, 3, 5, 2, 4];               // 1. assignment
sort(nums);                                // 2. call function
console.log(nums);                         // 11. print sorted
.as-console-wrapper { top: 0; max-height: 100% !important; }

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

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

What is the method for adjusting the time format?

Using the TIME data type, my data is currently displayed in the format hh:mm:ss (03:14:00). How can I change it to display in the format hh:mm (03:14)? The usual DATE type method does not seem to work: {{test.time | date: 'HH:mm'}} However, thi ...

Error encountered with MobileFirst version 8 and Angular JS v1.5.3 integration using Bootstrap

I am encountering an issue with my Cordova application that integrates with MobileFirst Platform version 8, Ionic version 1.3.1, and AngularJS version 1.5.3. Upon bootstrapping AngularJS to connect the app to MobileFirst Platform, I encounter the following ...

Place the token within the Nuxt auth-module

Working on a project using the Nuxt auth-module. The Login API response is structured like this: data:{ data:{ user:{ bio: null, createdAt: "2021-06-29T12:28:42.442Z", email: "<a href="/cdn- ...

Is there a way for me to customize the appearance of the Material UI switch component when it is in the checked

I am seeking to customize the color of the switch component based on its checked and unchecked state. By default, it displays in red. My goal is to have the "ball knob" appear yellow when the switch is checked and grey when it is not. This styling must be ...

Transforming PHP JSON into JavaScript with getJSON

Hello everyone, I must admit my lack of knowledge in javascript/ajax as I am struggling to convert this php json into a javascript function $json = file_get_contents('http://videoapi.my.mail.ru/videos/mail/alex.costantin/_myvideo/4375.json'); ...

Demonstrating the transformation of child elements into parent elements through angular 6 ngFor

I have a JSON array dataset where each object may contain nested arrays. In order to display the inner nested array elements as part of the parent array using Angular's NgFor, I need to format the input like this: [{ 'id': 1, 'tit ...

Steps for changing a component's properties when the component serves as a property

The scenario I'm facing involves a component that receives a prop named button. This button prop is essentially a Component itself, containing various other props within it. My goal is to override the specific prop called type within this nested struc ...

Transitioning NodeJS from local development to a live website

After successfully creating a site using NodeJS with one-page HTML/jQuery, everything is functioning properly on localhost. However, I am facing issues when trying to put the site online at www.xxxx.com. I already have a registered .com domain, but I am un ...

Exploring the implementation of Chain Map or Chain Filter within an Angular Http request that delivers a promise

I have a dataset in JSON format that I am working with, and I need to filter out specific key values using lodash. I want to reject multiple keys that I don't need. My initial approach is to either chain the map function and then use the reject funct ...

Looking for guidance on building a real-time React application with automatic data fetching linked to a nodejs backend

I have a simple question, I have developed an app that retrieves data from a backend server, Now, the app needs to be accessed and edited by multiple users simultaneously while ensuring that all changes made to the list are reflected in real-time for ever ...

I currently have two responsive menus and I'm trying to figure out how to modify the javascript so that when one menu is opened, the other

I am facing an issue with my responsive menus on a webpage, similar to the example provided in the jsfiddle link below. Currently, when one menu is open and I click on another, both remain open. How can I modify the JavaScript code so that when one menu op ...

Using javascript to overlay and position many images over another image

I've searched extensively but haven't been able to find any relevant answers here. Currently, I am developing a hockey scoring chance tracker. My goal is to display an image of the hockey ice where users can click to mark their input. Each click ...

In JavaScript, you can use the document.cookie property to delete specific cookie values identified by their names and values

Within my JavaScript code, I am working with a cookie that contains multiple names and values: "Token=23432112233299; sessionuid=abce32343234" When I download a file from the server, a new cookie is added to the document, resulting in the following cooki ...

Unable to access the website's source code

It's frustrating when I can't view the source code of certain websites, such as this one: . When I try to right-click and select "View Source", only a portion of the code is displayed, which isn't the proper source code for the page. Alth ...

"Implementing a nested drawer and appbar design using Material UI, along with incorporating tabs within

I am currently working on an app that includes tabs for different files, each of which requires its own drawer and appbar. I found a codesandbox example that is similar to what I am trying to implement. Here is the link to the codesandbox One issue I hav ...

Combining jQuery dataTables and Codeigniter for dynamic rendering using sAjaxSource

I am currently facing an issue while working with dataTables in Codeigniter. I keep encountering the following error message: array_push() expects parameter 1 to be array, null given The resulting output is {"aaData":null} My desired outcome should look ...

Exploring the intricacies of JSON object retrieval

I'm currently working on a form that allows users to submit address details for a selected location. However, before submitting the form, I want to give the user the ability to preview the address that will be sent. The addresses are stored within a J ...

Activate a button only when a value is inputted into a text box associated with a chosen radio button

I'm facing a challenge with my radio buttons and sub-options. When a user selects an option, the corresponding sub-options should be displayed. Additionally, I want to enable the next button only when text is entered in all sub-option text boxes for t ...

Experimenting with directive using jasmine

I've been working on this directive but I'm having trouble writing the jasmine test for it. Any suggestions? import { Directive, Output, EventEmitter, HostListener } from '@angular/core'; @Directive({ selector: '[ctrlKeys]&apos ...