简体   繁体   中英

How to Sort an Array of Numbers of String Datatype without using Inbuilt sort() and atoi method in JavaScript

I am trying sort the below given Array without converting the strings to number(without atoi function) and also without using sort() inbuilt function

inputArr = ["1","2","10","3","21","15"]

let len = inputArr.length;
    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len; j++) {
            if (inputArr[j] > inputArr[j + 1]) {
                let tmp = inputArr[j];
                inputArr[j] = inputArr[j + 1];
                inputArr[j + 1] = tmp;
            }
        }
    }
    return inputArr;

But the above code doesn't sort the numbers in correct order

Output Expected: ["1","2","3",,"10","15","21"]

You seem to be approaching the problem by using a BubbleSort, so tried to come up with a solution using the same algorithm.

The issue is with your comparison.

You will see that

"1" < "10" === true

But

"2" < "10" === false

So you need to check each character of the string to determine whether the number is actually smaller or not. Here is the code:

    const arr = ["1", "2", "10", "3", "21", "15"];
    const len = arr.length;

    const isGreater = (num1, num2) => {
        if (num1.length < num2.length) return false;
        for (let i = 0; i < len; ++i) {
           if(num1[i] === num2[i]) continue;
           return (num1[i] > num2[i]);
        }
        return false;
    }

    for (let i = 0; i < len; ++i) {
        for (let j = 0; j < len - i - 1; ++j) {
            if (arr[j].length > arr[j + 1].length || isGreater(arr[j], arr[j + 1])) {
                let tmp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = tmp;
            }
        }
    }

    console.log(arr);

The function isGreater will do that check for you.

 inputArr = ["1","2","10","3","21","15"] const sorted = inputArr.sort((a, b) => Number(a) - Number(b)) console.log(sorted);

const a = ["1","2","3",,"10","15","21"]; a.sort((x, y) => x-y);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM