Master the art of using Insertion Sort in javascript with the help of Khan Academy

Seems like I am almost there with solving this problem, but my code isn't running as expected. Can someone offer some feedback and point out where I went wrong?

var insert = function(array, rightIndex, value) {
    for(var j = rightIndex;
        j >= 0 && array[j] > value;
        j--) {
        array[j + 1] = array[j];
    }   
    array[j + 1] = value; 
};

var insertionSort = function(array) {
    for(var i = 1; i < array.length; i++){
        insert(array, array.length -1, i);
    }
};

var array = [22, 11, 99, 88, 9, 7, 42];
insertionSort(array);
println("Array after sorting:  " + array);
//Program.assertEqual(array, [7, 9, 11, 22, 42, 88, 99]);

When I use insert(array, array[i], i);, the output is:

Array after sorting: 22,11,12,100,89,10,8,43,5,,4,,1,,

Answer №1

Here is another approach to solving the insertion sort problem:


const insertValue = function(arr, index, val) {
    for(let j = index; j >= 0 && arr[j] > val; j--) {
        arr[j + 1] = arr[j];
    }
    arr[j + 1] = val;
};

const performInsertionSort = function(arr) {
    for(let i = 0; i < arr.length-1; i++){
        insertValue(arr, i, arr[i+1]);
    }
};

let numArray = [34, 56, 22, 78, 90, 10];
performInsertionSort(numArray);

Answer №2

It appears there is an issue that needs addressing:

Within the line

insert(array, array.length -1, i);
, it should actually be
insert(array, array.length -1, array[i]);

The mistake made was inserting the array index instead of the value

Additionally, a potential array out-of-bounds error exists in array[j + 1] = array[j]; since j starts from array.length -1. It would be more appropriate to use array[j] = array[j-1]; while ensuring j>0.

One final point: The rightIndex variable should be i for each iteration, not array.length -1.

Updated code snippet :

var insert = function(array, rightIndex, value) {
        for(var j = rightIndex;
                j > 0 && array[j-1] > value;
                j--) {
                array[j] = array[j-1];
            }   
            array[j] = value; 
        };

        var insertionSort = function(array) {
            for(var i = 0; i < array.length; i++){
                insert(array, i, array[i]);
            }

        };

        var array = [22, 11, 99, 88, 9, 7, 42];
        insertionSort(array);

Answer №3

Insertion sort is a sorting algorithm that involves dividing the initial unsorted array into two parts: the sorted part and the unsorted part. At first, the sorted part consists of just one element (an array with only one element is considered sorted). Elements are then selected one by one from the unsorted part and inserted into the correct position in the sorted part, gradually expanding the sorted part as each element is inserted.

var numbers = [34, 203, 3, 746, 200, 984, 198, 764, 9];

function insertionSort(arr) {
  var len = arr.length;
  for(var i = 1; i < len; ++i) {
    var tmp = arr[i];
    var j = i - 1;
    for(; j >= 0 && arr[j] > tmp; --j) {
      arr[j+1] = arr[j];
    }
    arr[j+1] = tmp;
  }
};

console.log(numbers);
insertionSort(numbers);
console.log(numbers);

Answer №4

Arriving a bit fashionably late to the event, it seems there are numerous methods to tackle this challenge, yet the golden figure on KA prefers a specific approach. Here is the solution that brought a smile to its face:

function insertValue(array, rightIdx, val) {
 for(let i=rightIdx; i >= 0 && array[i] > val ; i--){
    array[i+1] = array[i];
 }
 array[i+1] = val;
};

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

What is the process for applying a border to the chosen image within the ImageList of the MaterialUI component?

Currently, I have set up the images in a grid format using the and components from MaterialUI. However, I am looking to implement an additional feature where when a user clicks on a specific image from the grid, a border is displayed around that select ...

What steps can be taken to resolve the error message "t.onSubmit is not a function" that occurs upon form submission?

Upon submitting a form, it should trigger the onSubmit method function. However, an error is being returned instead: TypeError: "t.onSubmit is not a function". I've attempted to address this issue by researching similar problems and solutions provide ...

Using the ES6 filter method to iterate through a double nested array of objects

Struggling with filtering a nested array of objects and specifically stuck at the filter part. Any idea on how to eliminate one of the marks? this.state = { data: [ { id: 1, name: "Main", subs: [ { id: "jay", ...

Solutions for Showing Pop-up Tabs in React Native Webview

I have a website that displays content based on user subscription status. If the subscription is active, a book is loaded; otherwise, if it's expired, a specific page is shown: https://i.sstatic.net/HLv0B.png To enhance user experience, I preload th ...

concealing the upper header while scrolling and shifting the primary header upwards

Is there a way to use CSS to move the main header navigation, including the logo and links, on my website up when scrolling down in order to hide the top black bar header that contains contact information? The website in question is atm.truenorthmediasol ...

Employing aspect.around while actively monitoring for methods invoking one another

Seeking a solution to run specific code around the put() and add() functions for Dojo stores, I encountered an issue with JSON REST stores where add() simply calls put(): add: function(object, options){ options = options || {}; options.overwrite = fal ...

the attempt to send an array of data to the $.ajax function was unsuccessful

let myArray = []; myArray.push(someValue); let requestData = { action: myAction, array: myArray }; $.ajax({ type: "POST", data: requestData, url: requestUrl, success: handleSuccess, error: handleError }); When ...

Utilizing jQuery and ajax to invoke an MVC controller

Hi there, I am currently facing an issue with calling a method in my controller using ajax and jquery with parameters Controller: [HttpPost("{Id}")] public ActionResult PostComment(int Id, ShowViewModel model) { } View: I have a button named AddCommen ...

Navigating Users and Routing with Ionic Framework (AngularJS)

Currently, I am using Ionic for a new project and could use some guidance with routing (I'm relatively new to Angular). These are the states I have defined: $stateProvider.state('map', { url: '/map', views: { map: ...

Create a soft focus on the background sans any filters

I am in the process of developing a website and have implemented code to blur out the background: CSS #background{ background: url(img/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

Disabling a checkbox within an onClick event handler

I'm facing an issue where I have a checkbox with the type "checkbox" and I'm using JAWS to read it. The problem is that in IE11, JAWS reads a disabled checked checkbox as unchecked, which I believe is a bug in IE. To work around this, I need to r ...

Issue alert before running tests on component that includes a Material UI Tooltip

This is a follow-up regarding an issue on the Material-UI GitHub page. You can find more information here. Within my Registration component, there is a button that is initially disabled and should only be enabled after accepting terms and conditions by ch ...

Effortlessly Display or Conceal Numerous Table Columns Using jQuery

I have a small table where I want to hide certain details with a basic button... for instance, table { border-collapse: collapse; } th, td { border: 1px solid gray; padding: 5px 10px; } <button>Show/Hide Details</button> <table> ...

Stop the webpage from scrolling when clicking on a ui-grid field

Is there a way to prevent page scrolling when clicking on a row field in ui-grid? I'm working with a page that has ui-grid, and each row includes an anchor tag with a URL value linked and target="_blank" to open in a new tab like the example below: ...

Utilizing a jQuery AJAX request to invoke a web method within a

My goal is to integrate jQuery mobile into an existing ASP.NET webform application. I am currently considering using pure HTML controls to create the jQuery Mobile page. I am aware that when making an AJAX call, I can access code-behind static web methods, ...

Send a parameter to an Angular directive when clicked

I am working on a directive that will allow me to retrieve parameters upon clicking. I need to access the child data within the click event to determine if it has children or not. ..... html div ng-app="treeApp"> <ul> <treeparent>< ...

Custom positioning of Mui Snackbar in V5

I've been attempting to position a Snackbar in the top right corner with some customization for the top property, but I'm struggling to get it to display correctly. Here's what I've tried: import React from "react"; import { ...

What method can be used to incorporate expressions into Handlebars partials when dealing with parameters?

Is it possible to include expressions in partials parameters? I am trying to achieve something similar to this: {{> myPartial greeting=(i18n.greeting + "my text") }} ...

Incorporating React components into your current Django project

My goal is to enhance the interactivity of a specific part of my Django website by incorporating React components into the template HTML file. Instead of replacing the entire template with React, I want to focus on integrating React for its ease in handlin ...