Sorting algorithm for basic leaderboard using bubble sort

I'm in the process of developing a basic video game leader board that will arrange user scores against preset scores in descending order.

<html>
  <!Foundation Page for building our Javascript programs>
  <head>
    <title>The Foundation Page </title>
    <script type="text/javascript">
      function leaderboard()
      {
        var leaderboardarray = new Array (5);
        var n, temp;
        ok=false;
        var score 
        var rank

        score = 150

        leaderboardarray[1] = 50;
        leaderboardarray[2] = 60;
        leaderboardarray[3] = 180;
        leaderboardarray[4] = 120;
        leaderboardarray[5] = score;

        while(!ok)
        {
          ok = true
          for (n=1; n<=5; n=n+1)
          { 
            if (leaderboardarray [n]<leaderboardarray [n-1])
            {
              leaderboardarray [n] = leaderboardarray [n-1];
              ok = false;
            }
          } 
        }

        for (n=5; n>=1; n=n-1) 
          document.write (leaderboardarray [n] + "<br>");
      }

    </script>
  </head>head>
  <body BGCOLOR="WHITE">
    <h2>The Foundation Page </h2>
    <hr>
    <script LANGUAGE="Javascript"> leaderboard() </script>

  </body>
</html>

The program is showing the arrays correctly, but I am facing an issue where it does not output values from highest to lowest. Instead, when a higher value is inserted after another, it duplicates the same value. If anyone has suggestions on how to tackle this problem, please advise. I'm still relatively new to programming, so apologies if I'm missing something obvious. Thank you!

Answer №1

It is recommended to utilize Array.sort for sorting purposes.

Nevertheless, the issue with the provided code lies in the implementation of your bubble sort. It appears that instead of swapping elements, you are simply overwriting the smaller value with the larger one.

function bubbleSort(arr) {
  var n = arr.length, swapped, tmp;
  do {
    swapped = false;
    for (var i = 1; i < n; i++) {
      if (arr[i-1] < arr[i]) {
        tmp = arr[i];
        arr[i] = arr[i-1];
        arr[i-1] = tmp;
        swapped = true; 
      }
    }
  } while (swapped && n--)
}

a = [50, 60, 70, 80, 150, 120]

bubbleSort(a);
console.log(a);
// [150, 120, 80, 70, 60, 50]

Answer №2

If you're working with JavaScript without utilizing prototype or jQuery, consider replacing your while statement with the following code snippet:

leaderboardarray.sort(function(a, b){return b-a});

You can find a comprehensive guide on the JavaScript sort function at w3schools.

<HTML>
<!--#Foundation Page for building our Javascript programs#-->
<HEAD>
<TITLE>The Foundation Page </TITLE>
<!--fixed this-->
<SCRIPT type="text/javascript">
    function leaderboard()
    {

            var n, temp;
            ok=false;
            var score 
            var rank

            var score = 150

            var leaderboardarray = new Array(5);
                leaderboardarray[0] = 50;
                leaderboardarray[1] = 60;
                leaderboardarray[2] = 180;
                leaderboardarray[3] = 120;
                leaderboardarray[4] = score;

            leaderboardarray.sort(function(a, b){return b-a});
            var myContent = '';
            for (var n=0;n<5;n++) 
                myContent += leaderboardarray[n] + "<br>";

            document.getElementById("leaderBoard").innerHTML = myContent;
    }

    //call the function here


</SCRIPT>
</HEAD>
<!--#Using CSS#-->
<BODY style="background-color:#FFF;">
        <H2>The Foundation Page </H2>
        <HR>
        <!--#This is a placeholder#-->
        <div id="leaderBoard"><script type="text/javascript">leaderboard();</script></div>

</BODY>
</HTML>

Here are some improvements to your code that should be considered:

  • You had two head tags.
  • You were sorting your array and then displaying the output with a decrementing for loop. My approach sorts the array in descending order and displays the output in ascending order.
  • I started arrays at index 0 for simplicity in the for statements.
  • Replaced the bgcolor HTML tag with CSS
  • Updated the script tag to use type instead of language.
  • Instead of using document.write which can cause issues, I'm updating the content of a div element as a placeholder.

Take a look at this fiddle.

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

Guide to animating the height of a div using jQuery:

I'm hoping to create a cool animation effect where a certain part of a div expands to 100% width when clicked, and then reverts back to its original height on a second click. I've tried writing some code for this, but it's not working as exp ...

What is the best way to access and utilize the data stored in my database using mySQL, PHP, and JavaScript?

My Objective : When a user selects a location from the dropdown list, I want the function "newMark()" to place a marker on Google Maps; Current Achievements : The map is displayed along with the select field containing all locations saved in my database. ...

I tried moving the onchange(this) function from HTML to JavaScript, but I seem to have missed a parameter. The code ends

I'm currently building a website for a fictional ice cream shop to enhance my JavaScript skills. function hideAAndB() { var pickupDiv = document.getElementById("pickupDiv"); var deliveryDiv = document.getElementById("deliveryDiv"); pickupDi ...

Issue with FusionCharts rendering correctly arises when the <base> tag is present in the HTML head section

Combining AngularJS and FusionCharts in my web application has led to a unique issue. The upcoming release of AngularJS v1.3.0 will require the presence of a <base> tag in the HTML head to resolve all relative links, regardless of the app's loca ...

How can I use jQuery to target and modify multiple elements simultaneously

I've been struggling for the past couple of hours trying to use prop to change the values of two items in a button. One item updates successfully, but the other one doesn't and I can't figure out why. Here is the HTML: <input type=&apos ...

Efficiently merging two arrays in PHP using a foreach loop

I am currently working on merging product options that are stored in a database and grouping them by the same product_id using a foreach loop. stdClass Object( [id] => 22 [product_id] => 48 [values] => Array ( [0] => stdCla ...

Converting CSS code into JavaScript

I am currently working with the following code: .mr15 > * margin-right: 15px &:last-child margin-right: 0 I need help translating this code to Javascript. Should I use JQuery or pure Javascript for this scenario? Thank you. ...

Error encountered: _moment2.default.date is not a recognized function within the React application

I keep encountering an issue when attempting to utilize a date from Moment.js in the constructor, componentWillMount, or componentDidMount. The error message I receive is: Uncaught TypeError: _moment2.default.date is not a function It's worth noting ...

Bootstrap Dropdown Functionality Malfunctioning

Here is a simple piece of HTML code that I have created: <!doctype html> <html> <head> <meta charset="utf-8"> <title>.:Home Page:. The Indian Sentinel</title> <link rel="stylesheet" href=" ...

Accessing an Array from a service method in Angular and passing it to my main component

Within my api-service.ts, I have an array that holds some data. public getData():Observable<any[]> { return Observable.toString[ObsResult]; } Now, in the main component, I am attempting to call the getData() method to render the data in ...

"Utilizing MongoDB's aggregate function to filter data by specific

I'm attempting to calculate the average temperature and humidity from my JSON response at 15-minute intervals using the MongoDB Aggregate framework. However, I'm encountering a SyntaxError: invalid property id @(shell):2:0 This is the code I am ...

Creating a circular frame for your image to use as a Facebook profile picture

In the process of developing an input feature that allows users to upload file images for avatar changes, similar to Facebook's functionality. However, I am aware that Facebook utilizes a circular area for avatars and enables users to adjust the image ...

Encountering a blank page and error message on Vue JS while attempting to generate a JSON file within the

Recently, I encountered a peculiar problem while working on my Vue project using Vue UI in Visual Studio. Before connecting my API, I wanted to prototype and experiment with fake data. So, I decided to create a JSON file in the assets folder to store my m ...

Aurelia-powered DataTable plugin for effortless data updating

I'm currently utilizing the DataTables and DatePicker plugins along with Aurelia in my project. The goal is for the user to select a date, which will then prompt the data table to display the corresponding data for that specific date. However, I' ...

If the window width is less than the specified value, hide the DIV and replace it with a

I came across a discussion about hiding a div if the screen is narrower than 1024px, and I'm looking to implement something similar based on the quoted code below. Essentially, I want to hide one div (id="krug_wide") if the window width is less than 1 ...

What is the best way to extract user input from a bootstrap search bar and integrate it into an ajax request to fetch information?

I am currently utilizing HTML, Javascript, and bootstrap to develop a web application. However, I have encountered an obstacle. When using the code document.getElementById("input here"), it only returned an array of 0. My goal is to retrieve data from an A ...

I am facing an issue with the Ionic Framework where the Javascript function for JWPlayer only works after the page is reloaded. Can anyone help

I'm currently troubleshooting the use of JWPlayer for streaming videos in an Ionic app. However, I've encountered a problem. The player only seems to load when I refresh the page, rather than when I navigate through the list of videos. Here is ...

Tips for concealing overlay when the cursor hovers

Can anyone help me with a code issue I'm having? I want to hide an overlay after mouse hover, but currently it remains active until I remove the mouse from the image. Here is the code: .upper {position: absolute; top: 50%; bottom: 0; left: 50%; tra ...

Steps for selectively extracting objects from an array containing nested objectsNeed a way to isolate specific objects

Currently, I am working on a project in JavaScript and have created an array called folders that holds multiple objects: folders = [folder1, folder2, folder3...] Each object within the array has various properties, one of which is docs that is an array o ...

Using jQuery, input data into a textarea element

I need assistance in extracting text from an element and inserting additional attributes to the text. The modified text should then be displayed in another element when a button is clicked. In my code snippet, the console.log() method correctly logs the d ...