本文介绍了对字符串进行排序,无需任何内置方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不使用内置方法的情况下对javascript中的字符串进行排序,只是使用for和比较类似'a'>'b';



不起作用:

功能替换字符串(str,我,字符){返回str.substr(0,我)+字符+字符串。 substr(i + 1)} function swap(str,i1,i2){return replaceAt(replaceAt(str,i1,str [i2]),i2,str [i1]);} function sort(str){var sorted =海峡; for(var i = 0; i



伪代码或书籍, !

解决方案

你的代码没有应用任何排序算法逻辑,我推荐你至少读1来解决你的问题。 p>

以下程序使用。



swap 替换
$ p $ 函数sort(str){
var sorted = str;
//对于(var j = i + 1; j if(str [i] str = swap(str,i,j)
}
}
}
return str;
}

console.log(sort(zaasfweqrouoicxzvjlmmknkniqwerpopzxcvdfaa));
//输出:aaaaccdeeffiijkklmmnnoooppqqrrsuvvwwxxzzz


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!

解决方案

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

这篇关于对字符串进行排序,无需任何内置方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:48