Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort string without any builtin methods

I want to sort a string in javascript without using a built in method, just by using for's and comparisons like 'a' > 'b';

Something that doesn't work:

function replaceAt(str, i, char) {
    return str.substr(0,i) + char + str.substr(i + 1)
}

function swap(str, i1, i2) {
    return replaceAt(replaceAt(str, i1, str[i2]),i2,str[i1]);
}

function sort(str) {
    var sorted = str;
    for (var i = 0; i < str.length; i++) {
        if (str[i] > str[i + 1]) {
            str = swap(str, i, i+1)
        }
    }
    return str;
}

Pseudo-code or books, courses recommendations on programming are welcome!

like image 215
TaoJS Avatar asked Feb 01 '26 12:02

TaoJS


1 Answers

Your code is not applying any sort algorithm logic, I recommend you to read atleast 1 to solve your problem.

Below is the program, which produces the expected output from your program using selection sort.

swap and replace functions works fine.

function sort(str) {
    var sorted = str;
    //Selection sort
    for (var i = 0; i < str.length; i++) {
        for(var j = i + 1; j < str.length - 1; j++) {   
            if (str[i] < str[j]) {
                str = swap(str, i, j)
            }
        }
    }
    return str;
}

console.log(sort("zaasfweqrouoicxzvjlmmknkniqwerpopzxcvdfaa"));
//output: aaaaccdeeffiijkklmmnnoooppqqrrsuvvwwxxzzz
like image 132
rajuGT Avatar answered Feb 03 '26 02:02

rajuGT