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

Facing compatibility problems with JavaScript and Cascading Style Sheets in Google Chrome?

Welcome to the site . Let's address a couple of issues with JavaScript and CSS: Firstly, the JS code seems to be malfunctioning only in Chrome, throwing an error that reads: 'Uncaught TypeError: Object [object Object] has no method 'on prij ...

Is there a way to incorporate jQuery into SharePoint 2010?

I am encountering an issue with linking my HTML page to our organization's SharePoint 2010 portal. All necessary files (CSS, images, jQuery) are stored in the same document library. While the CSS is functioning properly, I am facing challenges with ge ...

Utilize Laravel 8 and Vue Js to dynamically showcase retrieved data in input fields

I am facing a challenge with my Laravel 8 registration form using Vue js. Before submitting the form, I need to verify if the referring user exists in the database. If the user is found, I want to dynamically display their full name in an input field upon ...

Exploring the effectiveness of testing Svelte components

Looking to test a component that utilizes a third-party module without mocking the imported components? Check out this example: // test.spec.ts import Component from "Component"; describe('Component', () => { test('shoul ...

Switch to display only when selected

When I click on the details link, it will show all information. However, what I actually want is for it to toggle only the specific detail that I clicked on. Check out this example fiddle Here is the JavaScript code: $('.listt ul').hide(); $( ...

Assigning an identification number to specify the type of Chip

I am currently working on a project involving Material UI "Chips" that contain text and serve as references. Within the context of my project, I have Chips for both White Advantages and Black Advantages sections. However, there are instances where these Ch ...

Tips for displaying only a list of folders in elfinder, a jquery file management plugin

Currently, I am working on enhancing the features of a file manager plugin that allows users to manage their folders effectively. One key functionality of the plugin is the ability for users to share specific folders with others. However, if a folder has n ...

Error: The JavaScript function you are trying to use is not defined

Hi there, I'm new to javascript and angularjs. I've created a function in my controller to open a website when clicking on a button. However, I'm encountering an error message saying ReferenceError: openWebsite is not defined when trying to ...

Generating an array of objects using Jquery from XML data

I need assistance with extracting data from XML text nodes stored in a variable and then creating an array of objects using jQuery. The XML data I have is as follows: var header = ['name', 'data1', 'data2']; var data = &apos ...

Is it possible to manipulate the attribute of an object using Object.defineProperty when a value is passed as a function parameter?

As I delve into understanding reactivity in Vue, the concept of how reactivity is achieved when passing a value as a function parameter perplexes me. //here is the actual code snippet var obj = {a: 'aa'} function reactive(obj, key, value) { ...

Tips for creating a concise summary of written content

I am interested in creating an AI-powered summary generator for text input within a textarea element. Below is the HTML code snippet I have been working with: <textarea id="summary">Enter your text here</textarea> If you hav ...

Trouble arises when accessing GET form in php/Ajax

I am in the process of creating a dynamic website. At the top, I have an input form that, when submitted, should display the output from an asynchronous request to a PHP page using echo to show what was submitted. Unfortunately, it's not functioning ...

the div background is limited to the exact size of the text, not filling the entire

Currently, as I work on my web page using react.js, I'm facing the challenge of implementing a full-size background. Despite my efforts, the background only occupies the size of the text within the div. Here is the snippet of code I am working with: a ...

What is the solution for displaying just a single panel?

Is there a way to ensure that only the hidden text is displayed when clicking on the button within each panel? Currently, both panels are being revealed simultaneously... import React, { useState } from "react"; import "./styles.css"; export default func ...

Content obscuring dropdown menu

I am currently working on a screen design that resembles the following: return ( <SafeAreaView> <View style={styles.container}> <View style={styles.topContainer}> <View style={styles.searchFieldContainer}> ...

Can you explain the distinction between key and id in a React component?

I have included this code snippet in the parent component. <RefreshSelect isMulti cacheOptions id='a' key = 'a' components={makeAnimated()} options={th ...

Clicking on a date in Vue.js Fullcalendar

My goal is to retrieve a date value from the onDateClick function of fullCalendar using vue.js and then pass this data to a prop that can be stored in my backend via Laravel. However, I am encountering various undefined errors no matter how I approach th ...

What are some ways to enhance the functionality of the initComplete feature in Dat

$('#example').dataTable( { "initComplete": function(settings, json) { alert( 'DataTables has finished its initialisation.' ); } } ); Is there a way to extend the initComplete function for other languages? $.extend( true, $.f ...

Stop the setTimeout function after redirecting in the controller

I am experiencing an issue with my AJAX call as it keeps triggering my controller repeatedly. AJAX function <script type="text/javascript> var stopTime =0; var scoreCheck = function () { $.ajax({ url: "<?php echo 'http:// ...

Tips for adding a CSS marker to the Videogular timeline at a designated time

My HTML player application allows users to search for a term and then displays the results along with the time when those words appear. By clicking on a specific sentence, the HTML player will start playing from that location. However, I would like to enha ...