Sorting an array using the Insertion sort algorithm in JavaScript / An undefined function

Currently, I am in the process of developing a JavaScript file that includes an insertion sort function, a method to validate a sorted array and return true or false, and a reverse insertion sort function that operates from the end of the array index towards the beginning. Below is the code snippet I have been working on:


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

function reverseInsertionSort(arr) { 
    for(var i = arr.length; i > 1; i--) 
    { 
        var val = arr[i]; 
        var j;
        
        for(j = i; j > 0 && arr[j-1] > val; j--) {
            arr[j] = arr[j-1]; 
        } 
        
        arr[j] = val;
    } 
}

var length = Math.floor(Math.random()*100)+1;
var arr = new Array();

for(let i = 0; i < length; i++) {
    arr.push(Math.floor(Math.random()*10000)+1);
}

console.log(arr);

var sortedArr = insertionSort(arr);
console.log(sortedArr);

console.log("And with reverse \n");

var reverseSortedArr = reverseInsertionSort(arr);
console.log(reverseSortedArr);

I am currently facing an issue where sortedArr turns out to be undefined when I output it using console.log. It seems like the problem lies in my function being "undefined", although I have clearly defined it above. I'm puzzled by this inconsistency.

Answer №1

The insertionSort function you are using does not actually return a value; rather, it modifies the array directly as an argument. So instead of writing

var sortedArr = insertionSort(arr)
, simply call insertionSort(arr) and then use console.log(arr).

Answer №2

Make sure to include a return statement in the function for it to work properly. If there is no return, you will get an undefined result.

function insertionSort(arr) { 
    for(var i = 1; i < arr.length; i++) { 
        var val = arr[i]; var j; for(j = i; j > 0 && arr[j-1] > val; j--) {
            arr[j] = arr[j-1]; } arr[j] = val; }
   return arr; }
function reverseInsertionSort(arr) { 
    for(var i = arr.length; i >1; i--) 
    { var val = arr[i]; var j;
        for(j = i; j > 0 && arr[j-1] > val; j--)
            { arr[j] = arr[j-1]; } arr[j] = val;
            } return arr}
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
  arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
    
var sortedArr = insertionSort(arr);
console.log(sortedArr);
console.log("And with reverse \n");
var reverseSortedArr = reverseInsertionSort(arr);
console.log(reverseSortedArr);
//console.log(sortCheck(sortedArr));

Answer №3

It is crucial to ensure that you are returning the array from the function(s). If you fail to do so, storing the result of the function in a variable will not provide any meaningful outcome.

function implementInsertionSort(array) { 
    for(let i = 1; i < array.length; i++) { 
        let value = array[i]; 
        let j; 
        for(j = i; j > 0 && array[j-1] > value; j--) {
            array[j] = array[j-1]; 
        } 
        array[j] = value; 
     } 
    return array
}

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

Generating hyperlink regions dynamically

I am looking to create an image with a link map that will contain multiple areas that need to be updated frequently. Instead of constantly recreating the areas every few seconds, I want to generate them only when the user clicks on the image. I initially ...

After a span of two minutes, the Node.js and Express server terminates the connection

I am currently working with Express 4.X and Node.js 0.12. One of the routes in my application is responsible for uploading and processing files. However, I have encountered an issue where some file uploads are taking longer than the default 2-minute timeo ...

Activate a button utilizing jQuery keyboard functionality

Here is what I have accomplished so far: http://jsfiddle.net/qEKfg/ I have created two buttons that activate on click and resemble keyboard keys. My goal is to make them animate only when the corresponding keys (CTRL and ...

Fixed positioning of a div causes it to move further away when zooming out

Greetings to all! I am looking to achieve a scrolling effect for a div area as I scroll down the page. To accomplish this, I have utilized the CSS property position:fixed to lock the div area within another div called "page". Below is the corresponding CSS ...

Verifying the user's email and password for authentication

Is there a way to verify the authenticity of the email and password entered in the form, so that I can redirect to a new page? Unfortunately, upon reloading the page, the validation process seems to fail in checking whether the user email and password are ...

Is there a way to create a Swiper slider similar to the one used in the App Store

I am looking to create a slider using Swiperjs similar to the carousel on the Apple App Store (seen on the Games tab). I attempted to implement it using Vue Swiper, a package for vue, as shown below: HTML code: <div id="app"> <h1>Slider< ...

Issue: A malfunction was encountered during the rendering of the Server Components

Whenever I deploy my application to Vercel, I encounter the following error: production An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive detail This issue only manifests on ...

Exploring the distinctions between Django template variables and JavaScript variables

I am currently trying to populate a table in a Django template. The challenge I am facing is comparing cell values between a JavaScript variable and a Django template variable within the same context. Is there a way to perform this comparison without conve ...

JavaScript image element loaded but still has a height of 0

This particular issue is causing frustration as it seems to only work with a specific set of images and not with others. The object in question is: function PreLoader(toLoad, parent, images) { var errored = 0; var loaded = 0; var toLoad = toLoad; ...

What are some effective ways to utilize customvalidator for performing clientside validation on two input fields?

I attempted to implement a asp:CustomValidator along with client-side JavaScript in order to validate that the user does not input the same new password as the old password using the following code... <script type="text/javascript"> function ...

Invoke index functions within a component

I have a widget/component written in Angular 4 within the index.html file. Before and after this angular app, there are various HTML elements due to the nature of it being an additional component for the website. The head section of the index file include ...

Dragging the entire ForceDirected Graph in D3.js is not functioning

tag, I am currently working on implementing a D3 force directed graph using D3 v6 and React. The graph includes features such as zoom functionality and draggable nodes. However, as the graph can become quite complex and large due to dynamic data, I aim to ...

jQuery.post() function encounters issues with data not being properly posted

I am currently tackling a project that involves sending JSON data to a specific URL. I've been attempting to utilize the jQuery.post() method for this task, but I've run into a couple of roadblocks. The initial issue I'm facing is: jQuery. ...

Display a div using JavaScript when the mouse moves and make it follow the cursor

In my application, I have a set of customer records displayed as rows in a table. I am looking to implement a feature where, upon hovering over a record (row), a div will pop up showing more detailed information about that specific record. This hover-over ...

A button paired with a selection menu for a seamless user experience

One interesting feature I have implemented is a dropdown that filters records on an HTML table without the need for a button. The filter functionality works flawlessly even without a button to confirm the selection. public selectedBrand: any; public onCha ...

implementing a SetTimeOut function following the clicking of a button

Hey there, I've been working on a code snippet that switches the display state from block to none with an onClick function. However, I'm looking to add a delay before the state change happens so that there's time for an animation effect to ...

AngularJS ng-repeat causing data binding to constantly refresh

If I were to have a $scope setup similar to this: $scope.array = [ { a: 1, b: 2 }, { a: 2, b: 1 }]; And a corresponding view: <div>A: <div ng-repeat="obj in array">{{obj.a}}</div> </div> My question is, if the AngularJS watche ...

Error message: SIGSEGV Signal Caused by a Problem on Geeks for Geeks Platform

While attempting to solve a problem on Geeks for Geeks using a brute force approach, I encountered a task to find the leaders in an array of positive integers. A leader in the array is defined as an element that is greater than or equal to all elements to ...

Exploring a new approach to organizing data with LocalStorage and AngularJS

I developed an application that utilizes LocalStorage to store data. The issue I encountered was storing a large number of objects under a single key, causing the DOM to become blocked. This is due to the necessity of parsing and stringifying the JSON dat ...

Having difficulty retrieving objects within a foreach loop of object keys that do not meet the criteria of the string.prototype.replace method

Currently, I am working on looping over objects within a key:value array in JavaScript to use the string.prototype.replace method for paths to JS files in GulpJS concat tasks. The objective is to generate a list of paths that GULP can utilize, but they re ...