快速排序
var ary = [3,2,1]
function quick(ary) {
if(ary.length<=1){
return ary
}
let centerIndex = Math.floor(ary.length/2);
let centerValue = ary.splice(centerIndex, 1)
let leftAry = [];
let rightAey = [];
for(var i =0; i<ary.length;i++){
var cur = ary[i];
if(ary[i]<centerValue){
leftAry.push(cur)
}
else {
rightAey.push(cur)
}
}
return quick(leftAry).concat(centerValue, quick(rightAey))
}
console.log(quick(ary))
冒泡排序
var ary= [12, 23, 14, 25, 11, 13];
function fn(ary){
for(var i=0;i<ary.length-1;i++){
for(var j=0;j<ary.length-1-i;j++){
if(ary[j] < ary[j+1]){
var temp = '';
temp = ary[j];
ary[j] = ary[j+1];
ary[j+1] = temp
}
}
}
return ary
}
console.log(fn(ary))
console.log(ary)
新插入排序
var ary = [15, 13, 14, 11, 23, 19];
function insert(ary) {
let newAry = [];
newAry.push(ary[0]);
for (var i = 1; i < ary.length; i++) {
var cur = ary[i];
for(var j = newAry.length-1;j>=0;j--){
if(cur>newAry[j]){
newAry.splice(j+1, 0, cur);
break;
}
if(j === 0){
newAry.unshift(cur)
}
}
}
return newAry
}
console.log(insert(ary))
数组去重
let ary = [1,21,2,3,8,2,2];
for(var i=0;i<ary.length;i++){
for(var j=i+1;j<ary.length;j++){
if(ary[i] === ary[j]){
ary.splice(j,1);
j--;
}
}
}
console.log(ary);
var arr = [1,2,2,3,4]
var set = new Set(arr) // {1,2,3,4}
var newArr = Array.from(set)
console.log(newArr)
var arr=['h','e','l','l','o','2',1,2,1,3,2];
arr.sort(function(a,b) { return a-b; } );
for(var i=0; i<arr.length-1; i++){
if(arr[i] === arr[i+1]){
arr.splice(i,1);
i--;
}
}
console.log(arr)
Debugger 是个好东西,要学会用它。