题解 | 字符串排序

字符串排序

https://www.nowcoder.com/practice/5af18ba2eb45443aa91a11e848aa6723

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
    // Write your code here
    const theLength = await readline()
    // 存放所有字符串。
    const theList = []
    for(let index=0;index<theLength;index++){
        const item = await readline()
        theList.push(item)
    }
    // 冒泡排序,第一个循环保证正好循环够数组长度的值。
    for(let index1=0;index1<theList.length;index1++){
        // 第二个循环保证,数组最后一项一定是最大的。之所以要减1,是因为要当前项和后一项比较。优化的话,就是index1每循环一次,最后一项就必定是最大的一个数值。即不取【index2<theList.length - 1】,而是用【index2<theList.length - index2】。
        for(let index2=0;index2<theList.length - 1;index2++){
            if(theList[index2]>theList[index2+1]){
                const theMax = theList[index2]
                theList[index2] = theList[index2+1]
                theList[index2+1] = theMax
            }
        }
    }
    for(let index=0;index<theList.length;index++){
        console.log(theList[index])
    }

}() 

全部评论

相关推荐

牛客62533758...:华为不卡双非,而是卡院校hhhh
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务