Why isn't my code working? Issues with Insertion Sort algorithm

The functionality of the insertion sort seems to be malfunctioning with this error message: An issue occurred as a function is taking longer than expected to execute. Are there any errors present in your code?

// Code snippet for insertion sort
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 = 0; i < array.length ; i++)
    {
        insert(array,i,array[i+1]);
    }
};

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]);

Answer №1

Your issue lies in selecting array position as [i+1] and [j+1]

Revise

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; 
};

to

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; 
    };

and

 insert(array, i, array[i+1]);

to

 insert(array, i, array[i]);

Answer №2

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

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

var numbersArray = [22, 11, 99, 88, 9, 7, 42];
performInsertionSort(numbersArray);
console.log(numbersArray);

Make sure to adjust your loop iterations when calling the insert() function with i + 1.

Answer №3

To improve the insertionSort function, consider iterating through the array in reverse order:

const insertionSortReverse = function(arr) {
  for (let i = arr.length - 1; i >= 0; i--) {
    insert(arr, i, arr[i + 1]); 
  } 
};

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 code to hide text once an HTML5 video has completed loading?

Is there a way to display "Video Loading" with a 75% opaque background over an HTML5 video, and then have both the text and background disappear once the video has finished loading? If so, how can I achieve this? Thank you for your time and effort! You ca ...

What's the best way to showcase the time on the x-axis of a Flot line graph?

My goal is to display time intervals between the minimum and maximum values within a specific time range. For example: 2015-04-30 10:20:00 and 2015-04-30 10:30:00 on the x-axis. I need to fetch values from a database where the datetime is stored in the fo ...

Substitute the words for translation

I recently launched an online store using Volusion. However, I am facing an issue with the checkout page where it displays 'Your Cart,' which I need to change as I will have different translations. I have tried to locate the code responsible for ...

What is the process for issuing https requests with SuperAgent?

In my React Native Android project, I am utilizing SuperAgent, which works similarly to Node.js. My goal is to make an API call using the https protocol. However, when I simply use the following code: Req = SuperAgent .get(‘https://url...') ...

Logging into a website using Ajax technology

Check out this screenshot of the console.As a novice in json and Ajax, I am attempting to create a login functionality for my website. However, I am encountering issues and can't figure out why it isn't working. login-register.js function login ...

Retrieving every element within a specific HTML tag

I'm working with the following code snippet: <div id="container"> Lorem ipsum dolor sit amet <p>This is a paragraph</p> <br /> <span>This is a span</span> Lorem ipsum dolor sit amet </div> How can I retrieve ...

Retrieving a specific element from a JSON array in Java

Having trouble retrieving the value of a specific attribute from a JSON file - all I get is the entire array. Here's an example of the JSON file: { "head": { "vars": [ "type1" , "pred" , "type2" ] } , "results": { "bindings": [ ...

REST operations are malfunctioning while other methods are functioning correctly

It's quite strange, but I'm clueless about what could be causing this chaos. Here's the code snippet I'm working with: var express = require('express'); var router = express.Router(); var mongoose = require('mongoose&ap ...

What is preventing me from manipulating this Object outside of the ngOnInit() function?

I've been working on a project that involves fetching data from the server and manipulating it within the .ts file. However, I seem to be facing a common issue related to Typescript/angular concepts that I'm struggling to grasp...I would really a ...

Experimenting with the useDebounceCallback hook through Jest testing

Currently, I am experimenting with testing debounce functionality using Jest in a component that utilizes URL parameters for search. The function handleSearch makes use of the useDebounceCallback hook from usehooks-ts (which internally uses lodash debounce ...

Ways to retrieve object in Javascript

I retrieved this data object from a JSON file source. { "Apple": "Red", "Orange": "Orange", "Guava": "Green", } Afterward, I transformed it into an Object using: var data = JSON.parse(dataFromJson); which resulted in a JavaScript object ...

Material UI Table dynamically updates with Firestore real-time data

My current code aims to update a Material UI table in real-time with data from a Firestore database. I can fetch the data and store it in an array, but when I assign this array to the table data, nothing changes. I've heard that I should use states fo ...

showcasing JSON data in an HTML table with pure JavaScript

I am currently utilizing vanilla JS to send a client request to a REST web service that I have designed. The GET method I have implemented returns a list of books (List) in JSON format: 0: {name: "To Pimp a Butterfly", isbn: "ACBCDDSA", availableCopies: 1 ...

Tips for converting file byte code to file form data

From one folder I am retrieving a file and uploading it to another server. However, when I extract the file from the first folder, I receive a byte code representation of that file. The API for uploading the file to the second folder requires FormData as a ...

Searching for all occurrences of a user-specified search term within a string array using C++

I'm currently working on an assignment that involves loading a file containing books and their authors in sequential lines. I have successfully loaded the book titles into a book title array and the authors into a book author array. Here are the task ...

Is there a way to transfer the content from a textarea to a DIV in a specific format?

I have a text area and button set up to send the text area value (content) into <div id="rs"></div>, with each separate line of the textarea box being appended to the div as a new element when the Enter button or Line breaks occur. F ...

Errors in socket.on Listeners Result in Inaccurate Progress and Index Matching for Multiple Video Uploads

Is there a way to make sure that the `socket.on('upload-progress')` listener accurately updates the upload progress for each video as multiple videos are uploaded simultaneously? Currently, it appears that the listener is updating the progress fo ...

Executing complex queries in mongoose using the $or operator

I'm in search of an efficient way to create clean code for executing multiple complex queries. Within my MongoDB database, I have two collections: followers and events. The first query involves retrieving all followers associated with a specific use ...

What are the steps to splitting an array into separate integer and string arrays?

Can I split an array into two separate arrays containing strings and integers? Given Array: [ 0 => "4" 1 => "8" 2 => "15" 3 => "16" 4 => "23" 5 => "42" 6 => "apple" 7 => "water" ] Integer Array: [ ...

Ways to troubleshoot the issue of undefined navigator / window / document in Nuxt

I encountered an issue while trying to extract UserAgent and Retina information within a Nuxt application. The error message I'm receiving states that navigator/window is undefined. How can I retrieve this information within my Nuxt application? const ...