选择排序: 每次遍历列表,选出播放量最大的,放入另一个列表
假设你的计算机存储了很多乐曲。对于每个乐队,你都记录了其作品被 播放的次数。你要将这个列表按播放次数从多到少的顺序排列,从而将你喜欢的乐队 排序。该如何做呢?
/*
** 选择排序 O(n^2)
*/
const list = [
{name: "RADIOHEAO",count:156},
{name: "THE BLACK KEYS",count:35},
{name: "NEUTRAL MILK HOTEL",count:94},
{name: "BECK",count:88},
{name: "THE STROKES",count:61},
{name: "WILCO",count:111},
];
function selectionSort(list = []){
if(list.length <2 ){ return list;}
let sortlist = [];
while(list.length > 0){
let maxIndex = 0;
list.forEach((e,index)=>{
if(e.count > list[maxIndex].count){
maxIndex = index;
}
});
sortlist.push(list.splice(maxIndex,1));
}
return sortlist;
}
console.log(selectionSort(list));