题解 | #成绩排序#
成绩排序
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))
}()

OPPO公司福利 1105人发布