Are you sure all of your statements have been successful? This is the problem

Implement a selection sort algorithm that swaps values at a given position with the minimum value index. Use the swap and indexOfMinimum functions provided below. Despite following the logic, there seems to be an issue preventing the code from successfully running the assertion statement.

var swap = function(array, firstIndex, secondIndex) {
    var temp = array[firstIndex];
    array[firstIndex] = array[secondIndex];
    array[secondIndex] = temp;
};

var indexOfMinimum = function(array, startIndex) {

    var minValue = array[startIndex];
    var minIndex = startIndex;

    for(var i = minIndex + 1; i < array.length; i++) {
        if(array[i] < minValue) {
            minIndex = i;
            minValue = array[i];
        }
    } 
    return minIndex;
}; 

var selectionSort = function(array) {
    var j;
    var smallest;
    for(j = 0; j < array.length; j++)
    {
        smallest = indexOfMinimum(array, 0);
        swap(array , j , smallest); 
    }
};

var array = [22, 11, 99, 88, 9, 7, 42];
selectionSort(array);
println("Array after sorting:  " + array);

Program.assertEqual(array, [7, 9, 11, 22, 42, 88, 99]);

Answer №1

There seems to have been a bug in your code, please give this a try:

    var swap = function(array, firstIndex, secondIndex) {
    var temp = array[firstIndex];
    array[firstIndex] = array[secondIndex];
    array[secondIndex] = temp;
    };
    
    var indexOfMinimum = function(array, startIndex) {
    
    var minValue = array[startIndex];
    var minIndex = startIndex;
    
    for(var i = minIndex + 1; i < array.length; i++) {
        if(array[i] < minValue) {
            minIndex = i;
            minValue = array[i];
        }
    } 
    return minIndex;
    }; 
    
    var selectionSort = function(array) {
    var j;
    var smallest;
    for(j = 0; j < array.length; j++)
    {
    smallest = indexOfMinimum(array, j);
    swap(array , j , smallest); 
    }
    };
    
    var array = [22, 11, 99, 88, 9, 7, 42];
    selectionSort(array);
    console.log("Array after sorting:  " + array);
in selectionSort()

smallest = indexOfMinimum(array, 0);

This line should be corrected to:

smallest = indexOfMinimum(array, j);

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

Struggling to display the sorted array items on the screen?

Within the realm of my jsfiddle experiment, my aim is to organize items based on price from highest to lowest by utilizing the following function: function mySortingFunction() { var elements = [].slice.call(document.getElementsByClassName("price")); e ...

"Trouble with jQuery function when trying to call ajax - no results or response received

I'm currently working on developing a mobile app using icenium that utilizes JavaScript instead of its native language. The app is designed to display rows from a database containing event information. When the user clicks on an event, more details ab ...

Guide to comparing two TSX elements in a React + TSX environment

I am facing difficulties in comparing two React TSX elements. Despite being new to both React and TSX, I have tried copying and pasting the exact elements for comparison but it doesn't seem to work. Can you guide me on what might be causing this issue ...

Exploring the use of barcodes with node.js

Having some issues with generating a barcode using a barcode module from NPMJS called npm i barcode. I am getting an error message res is not defined even after following the instructions. Can someone please guide me in the right direction? Here is my code ...

Utilize the controller data to display information on a day-by-day basis

In my attempt to design a weekly calendar using AngularJS, I am facing challenges when it comes to inserting events into the 7 boxes representing each day of the week on the calendar. The current HTML structure is as follows: <div class="week"> ...

Tips on saving checklist values as an array within an object using AngularJS

I need help with storing selected checklist items as an array in a separate object. I want to only store the names of the checklist items, but I am struggling to figure out how to achieve this. Below is the HTML code: <div ng-app="editorApp" ng-contro ...

Customize the behavior of jQuery cycle with an <a> tag

Can the jQuery cycle be accessed through a link in order to override the i variable? I've come across examples that can achieve this, but not in a scenario like this where the cycle() function is located within a variable: $(document).ready(function ...

Arrange the timing difference

For a recent school project, I developed a program that measures the time required to sort an array of integers using a variety of sorting algorithms, including selection sort, bubble sort, merge sort, quick sort, heap sort, and radix sort. The integer arr ...

How to effectively share an object array between controllers when utilizing modal windows in AngularJS

I'm currently working with an array of objects that I need to share between two controllers, one of which involves a modal window. Check out the JavaScript code below: angular.module('MyApp', ['ngMaterial', 'ngMessages' ...

Error encountered while parsing Japanese characters using the express body-parser resulting in a bad control character issue

Currently, I am sending a large JSON string to a node express endpoint that is set up like this: import bodyParser from 'body-parser'; const app = express(); const jsonParser = bodyParser.json({ limit: '4mb' }); const databaseUri = &ap ...

Error: The 'replace' property of null cannot be read in select2

In my Node Express app, I am incorporating select2, and encountering an error when supplying an array as the data source with data: dataBase. The issue arises as Uncaught TypeError: Cannot read property 'replace' of null. Although using an ajax ...

Why is the button's ng-click changing the URL but not displaying the new view?

I recently started developing an IONIC application and encountered a challenge in navigating between pages upon clicking a button. Here is the progress I have made so far: In my index.html file, I have included various scripts and links for the applicatio ...

Using PHP to create multi-dimensional arrays and display them in a HTML table

Need help with this issue: Here is the array I'm working with: $tabel3 = array ( array ( "progdas" => "Java", "sks" => "3", "prior" => "2" ), array ( "progdas" => "C#", "sks" => "6", "prior" => "1" ), array ( "mat" => "Dasar", ...

Injecting a service into an Angular constant is a straightforward process that involves

Is it possible to define a constant that utilizes the $locale service? Since constants are objects, injecting them as parameters like in controllers is not an option. How can this be achieved? angular.module('app').constant('SOME_CONSTANT&a ...

How to set the value of an `<input type="date"` in jQuery

Having trouble figuring out why this code isn't functioning properly. The input field I'm using is a simple 'input type="date"' setup like this.... <input type="date" name="Date"/> I am attempting to have the value automatically ...

Filtering URLs using Firefox extension

As the page loads, multiple HTTP requests are made for the document and its dependencies. I am looking to intercept these requests, extract the target URL, and stop the request from being sent if a specific condition is met. Additionally, plugins may als ...

Retrieving a specific document from an array that meets a specific query using MongoDB in JavaScript

I have a collection of data stored in MongoDB structured like this: users: { { user_id: 1000, activities: [ {id: 1, activity: 'swimming'}, {id: 2, activity: 'running'}, {id: 3, activi ...

Creating a leaderboard with the help of arrays

Our teacher assigned us the task of creating a JApplet with a high score feature. The challenge was to utilize an ArrayList containing 10 integer values. Upon pressing a JButton, these values would be shown in a JLabel. Additionally, users could input a n ...

Ways to alter the color of an icon when hovering over it

Is there a way to change the color of a material icon inside an IconButton material component when hovering over the IconButton? I've tried adding a class directly to the icon, but it only works when hovering over the icon itself and not the IconButto ...

Looking for a simple method to link JSON data to an svg element through Javascript?

Looking to harness the power of SVG for a basic graph creation, but uncertain about the process of assigning JSON data dynamically using a 'for loop' to draw rectangles within SVG. Seeking guidance on setting up 1 loop to assign each value for dr ...