题解 | #成绩排序#

成绩排序

https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b

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

void async function(){
    const n = parseInt(await readline());
    const rule = parseInt(await readline());
    const students = [];
    for(let i = 0; i < n; i++){
        let [name,score] = (await readline()).split(" ");
        students.push([name,parseInt(score)]);
    }
    //js内置的sort排序
    // if(rule){
    //     //0代表从高到低,1代表从低到高
    //     students.sort((a,b)=>a[1]-b[1]);
    // }else{
    //     students.sort((a,b)=>b[1]-a[1]);
    // }

    //手写排序:稳定的排序方式
    const compare = rule?((a,b)=>a[1]-b[1]):((a,b)=>b[1]-a[1]);
    for(let i = 0; i < n; i++){
        for(let j = 0; j < n-1; j++){
            if(compare(students[j],students[j+1])>0) [students[j],students[j+1]] = [students[j+1],students[j]];
        }
    }
    console.log(students.map(item=>item.join(" ")).reduce((pre,cur)=>pre+"\n"+cur))
}()

全部评论

相关推荐

2024-12-16 21:10
曲阜师范大学 Web前端
点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

更多
牛客网
牛客企业服务