Sort string without any builtin methods

不问归期 提交于 2019-12-23 15:50:55

问题


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!


回答1:


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



回答2:


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
array=[4, 10, 2, 9, 6, 3, 13, 5];
function arrayOperations()
{
    var count = array.length - 1,
        temp,
        j,
        i;

    for (j = 0; j < count; j++)
    {

        for (i = 0; i < count; i++)
        {

            if (array[i] > array[i + 1])
            {
                temp = array[i + 1];
                array[i + 1] = array[i];
                array[i] = temp;
            }

        }
    }
document.write("ascending order is <br>")
for(k=0;k<=array.length-1;k++){
    document.write(array[k]+ "<br>");
    }

document.write("descending order is <br>")
for(k=array.length-1;k>=0;k--){

        document.write(array[k]+ "<br>");
    }
document.write("biggest number is <br>")
for(k=array.length-1;k>=0;k--){

        if((array[k])>array[k-1]){
        document.write(array[k]+"<br>")
        break;
        }
    }
document.write("smallest number is <br>")
for(k=0;k<=array.length;k++){

        if((array[k])<array[k+1]){
        document.write(array[k]+"<br>")
        break;
        }
    }




    }




</script>
  <title></title>
</head>
<body>
array=[4, 10, 2, 9, 6, 3, 13, 5]
<br>
<input type="button" onclick="arrayOperations()" value="find">
</body>
</html>


来源:https://stackoverflow.com/questions/33266885/sort-string-without-any-builtin-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!