Sorting an integer without using string methods and without using arrays in JavaScript

In this problem, we need to sort the digits of an integer number without using string methods or arrays in JavaScript. We'll use mathematical operations and loops to extract, compare, and rearrange digits.

Understanding the Problem

Sorting an integer means arranging its digits in ascending or descending order. For example, if we have the number 784521, the sorted result would be 124578 (ascending) or 875421 (descending). We need to achieve this using only mathematical operations without converting to strings or using arrays.

Algorithm Overview

Our approach involves two main functions:

  • sortInteger() - Main function that extracts digits and calls the helper function
  • insertDigit() - Helper function that inserts each digit at the correct position

Step-by-Step Algorithm

Step 1: Extract each digit from right to left using modulo (%) and division operations

Step 2: For each extracted digit, find its correct position in the sorted number

Step 3: Insert the digit at the appropriate position to maintain descending order

Step 4: Continue until all digits are processed

Implementation

// Function to sort integer digits in descending order
function sortInteger(num) {
    if (num < 0) {
        // Handle negative numbers by returning -1
        return -1;
    }
    
    if (num === 0) {
        return 0;
    }

    let sortedNum = 0;

    while (num > 0) {
        // Extract the last digit
        const digit = num % 10;
        // Insert the digit at the correct position
        sortedNum = insertDigit(sortedNum, digit);
        // Remove the last digit
        num = Math.floor(num / 10);
    }

    return sortedNum;
}

// Helper function to insert digit at correct position for descending order
function insertDigit(num, digit) {
    if (num === 0) {
        return digit;
    }

    let newNum = 0;
    let multiplier = 1;
    let inserted = false;

    while (num > 0) {
        const currDigit = num % 10;

        // Insert digit if it's greater than current digit (descending order)
        if (digit > currDigit && !inserted) {
            newNum += digit * multiplier;
            multiplier *= 10;
            inserted = true;
        }

        // Add current digit to new number
        newNum += currDigit * multiplier;
        multiplier *= 10;
        num = Math.floor(num / 10);
    }

    // If digit hasn't been inserted yet, add it at the end
    if (!inserted) {
        newNum += digit * multiplier;
    }

    return newNum;
}

// Test cases
console.log("Original: 302541, Sorted:", sortInteger(302541));
console.log("Original: 123456789, Sorted:", sortInteger(123456789));
console.log("Original: 504030201, Sorted:", sortInteger(504030201));
console.log("Original: 1000, Sorted:", sortInteger(1000));
Original: 302541, Sorted: 543210
Original: 123456789, Sorted: 987654321
Original: 504030201, Sorted: 543210000
Original: 1000, Sorted: 1000

How It Works

The algorithm works by:

  1. Digit Extraction: Using num % 10 to get the last digit and Math.floor(num / 10) to remove it
  2. Position Finding: The insertDigit() function finds where each digit should be placed by comparing with existing digits
  3. Number Building: Using a multiplier to place digits in correct positions (units, tens, hundreds, etc.)

Complexity Analysis

Aspect Complexity Explanation
Time Complexity O((log n)²) Outer loop runs log n times, inner insertion also takes log n
Space Complexity O(1) Only constant extra space for variables

Key Points

  • No string conversion or array usage - purely mathematical approach
  • Handles edge cases like zeros and negative numbers
  • Sorts in descending order by default
  • Maintains digit positions using multiplier technique

Conclusion

This mathematical approach successfully sorts integer digits without using strings or arrays. The solution demonstrates how mathematical operations and careful position tracking can solve digit manipulation problems efficiently.

Updated on: 2026-03-15T23:19:00+05:30

985 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements