What is the most efficient method for arranging the numbers in a whole number?

Is there a more efficient method than storing the numbers in an array and using .sort() to arrange them?

Answer №1

If you want to optimize performance and avoid unnecessary string conversions, consider implementing counting sort for sorting integers based on their digits. This approach takes advantage of the fact that there are only 10 possible digits (0-9) in a number.

function countingSortDigits(n) {
    const count = Array(10).fill(0);
    for (; n; n = (n - n % 10) / 10) {
        count[n % 10]++;
    }
    for (let digit = 0; digit < 10; digit++) {
        for (let j = count[digit]; j; j--) {
            n = n*10 + digit;
        }
    }
    return n;
}

A comparison of execution times is provided below:

function toStringSort(n) { // Initial implementation 
    return parseInt(n.toString().split("").sort().join(""));
}

function countingSort(n) {
    const count = Array(10).fill(0);
    for (; n; n = (n - n % 10) / 10) {
        count[n % 10]++;
    }
    for (let digit = 0; digit < 10; digit++) {
        for (let i = count[digit]; i; i--) {
            n = n*10 + digit;
        }
    }
    return n;
}

function timeIt(f, repeat) {
    const start = performance.now();
    while (repeat--) f();
    return performance.now() - start;
}

const timing = { toStringSort: 0, countingSort: 0 };
// Generate random integers and measure execution time
for (let i = 0; i < 1000; i++) {
    let n = Math.floor(Math.random() * 1e15);
    timing.toStringSort += timeIt(toStringSort.bind(null, n), 1000);
    timing.countingSort += timeIt(countingSort.bind(null, n), 1000);
}
console.log(timing);

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

Triggering a server-side event handler in ASP.NET using client-side JavaScript

I need help with implementing a countdown timer in JavaScript. When the timer reaches 0 seconds, I would like the page to trigger the button1_click event handler. Here's the scenario: I am working on a quiz engine where the quiz responses need to be ...

What are the steps to resolve the DOMException error "Failed to execute 'open' on 'XMLHttpRequest': Invalid URL" in Angular HttpClient when making requests to a third-party server or API?

I am encountering the following issue: DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL while trying to perform a GET request to debounce.com import{HttpClient} from '@angular/common/http'; export {T ...

Exploring Angular's JavaScript Find Function

Here is a snippet of the code I've been working on: var myApp = angular.module('myApp',[]); //myApp.directive('myDirective', function() {}); //myApp.factory('myService', function() {}); myApp.controller('MyCtrl ...

We encountered an error while trying to locate the 'socket.io' view in the views directory

Having an issue with my nodejs server. Check out the code below: server.js global.jQuery = global.$ = require('jquery'); var express = require('express'), path = require('path'), menu = require("./routes/menu"); var ...

angular $stateProvider behaving unexpectedly with routing

Within my main file titled index.html, I have incorporated the following basic markup... <body ng-app="starter" ng-controller="AppCtrl"> <div ui-view></div> </body> In my separate file called app.js, I am utilizing $stateProvi ...

Show the loading icon once to indicate that the page is waiting for an AJAX call

I am currently setting up a table that is refreshed with new data every 4 seconds using AJAX. During the initial page load, I would like to show a loading message while waiting for the AJAX to complete. Currently, I have successfully displayed the loading ...

Leveraging TypeScript to Access Parameters in React Router

Currently, I am delving into the realm of TypeScript usage in my React projects and I have encountered a stumbling block when it comes to implementing React Router's useParams() feature. My import statement looks like this: import { useParams } from ...

Tips for eliminating inline scripts or HTML injections from input text using JavaScript or jQuery

Although this type of question may have been asked multiple times before, I am confident that this one is unique. On the server side, I have an Input TextArea control and I am attempting to eliminate all inline scripts or HTML injections. I have successful ...

What is the best way to alert a user before they navigate away from a page with content in a textarea?

I am attempting to recreate the functionality seen on textareas in Stack Overflow. UPDATE: Following the advice provided here, I have implemented something similar to the following: window.onbeforeunload = function() { var myTextArea = document.getE ...

JavaScript's "for of" loop is not supported in IE 11, causing it to fail

Here is a piece of code I'm using to select and remove a d3.js node: if (d.children) { for (var child of d.children) { if (child == node) { d.children = _.without(d.children, child); update(root); ...

iOS hover menu behavior: Close dropdown when the same element is tapped again on iPads

The navigation bar features categories such as: politics, economy, education Upon clicking on these categories, a dropdown menu appears with locations like: asia, europe, North America What I am looking for is this: If the user clicks (tabs) or hovers (o ...

Terminate the JWT token and automatically log out the user in the event of a banning or modification

Greetings fellow developers, I've been working on enhancing my application's user system to include functionality for administrators to upgrade an account's level (granting admin privileges if it reaches level 10) or ban users from the site ...

EC2 experiencing issues with Node cron execution

My setup involves running python and node scripts as cron jobs on EC2. Interestingly, the python scripts are executing without any issues, but the node scripts seem to be failing. When I manually activate the node scripts from the command line, they work p ...

Is it possible to access various image sizes and formats all from one centralized database location?

When it comes to sizes, there are several potential solutions that could be explored. One approach could involve using a suffix or prefix. For example: If there is just one path column in the database like 'images/example', different image sizes ...

Struggling with implementing a personalized zoom feature in React-Leaflet?

Looking to create a custom Zoom button using react-leaflet Below is the code I have been working on: import React from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { Map, TileLayer } from 're ...

Observe the present time in a specific nation

Is there an authorized method to obtain and showcase the current accurate GMT time instead of relying on the easily manipulable local time on a computer? I am looking for a reliable way to acquire the current time in hours/minutes, so I can make calculati ...

Getting the value of a checkbox from a MySQL database

Is there a way to print the entire contents of a textarea without any scroll bars, so that all text entered is visible? Currently, only the last few lines are showing when printed. I need the textarea to automatically resize for printing. <textarea cla ...

Do you have any suggestions on how to implement AJAX functionality on a website like this?

We have successfully created a comprehensive website with various pages, each offering unique features. For example, our galleries page utilizes jQuery Colorbox for viewing images, while other pages do not require this plugin (such as the 'About Us&ap ...

Using HTML5 Canvas to draw intersecting polygons

Recently, I came across a polygon drawing function that caught my attention: Polygon.prototype.draw = function(ctx) { ctx.save(); ctx.beginPath(); var v = this.vertices[0] ctx.moveTo(this.position.x + v.x, this.position.y + v.y); var i ...

How to exclude the port number from the href in a Node.js EJS template?

I have the following code snippet. I am trying to list out the file names in a specific directory and add an href tag to them. The code seems to be working fine, however, it still includes the port number where my node.js app is running. How can I remove ...