问题描述
我想在不使用内置方法的情况下对javascript中的字符串进行排序,只是使用for和比较类似'a'>'b';
不起作用:
伪代码或书籍, !
你的代码没有应用任何排序算法逻辑,我推荐你至少读1来解决你的问题。 p>
以下程序使用。
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: 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
和替换$ c
$ 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
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;
}
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