排序算法對於前端來講用的不是那麼多(sort除外...),可是一些比較常見的排序算法仍是須要知道的,下面分享一下常見的算法代碼實現javascript
let arr = [1,3,2,4,8,6,7,5];
function bubble(arr) {
let len = arr.length;
let temp;
for(let i=0;i<len;i++) {
for(let j=0;j<len-i-1;j++) {
// 相鄰元素比較
if(arr[j]>arr[j+1]) {
// 知足條件交互
temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
return arr
}
console.log(bubble(arr));// [1,2,3,4,5,6,7,8]
複製代碼
let arr = [1,3,2,4,8,6,7,5];
function select(arr) {
let len = arr.length;
let min,temp;
for(let i=0;i<len-1;i++) {
// 假設當前拿到的是最小值 min是索引
min = i;
for(let j=i+1;j<len;j++) {
// 找到最小值
if(temp>arr[j]) {
min = j;
}
}
// 當前值與最小值交換
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
return arr
}
console.log(select(arr));// [1,2,3,4,5,6,7,8]
複製代碼
let arr = [1,3,2,4,8,6,7,5];
function insert(arr) {
let len = arr.length;
let pre,temp;
for(let i=1;i<len;i++) {
// pre是前一個的索引
pre = i-1;
temp = arr[i];
// 不斷與前一個數比較,知足條件插入
while(pre>=0 && arr[pre]>temp) {
// 大值給小值賦值
arr[pre+1] = arr[pre];
pre--;
}
arr[pre+1] = temp;
}
return arr
}
console.log(insert(arr));// [1,2,3,4,5,6,7,8]
複製代碼
let arr = [1,3,2,4,8,6,7,5];
function merge(arr) {
let len = arr.length;
if(len<=1) {
return arr
}
let mid,left=[],right=[];
mid = Math.floor(len/2);
left = arr.slice(0,mid);
right = arr.slice(mid);
return mergeFn(merge(left),merge(right))
}
function mergeFn(left,right) {
let result = [];
while (left.length && right.length) {
if (left[0] <= right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
while (left.length)
result.push(left.shift());
while (right.length)
result.push(right.shift());
return result;
}
console.log(merge(arr));// [1,2,3,4,5,6,7,8]
複製代碼
let arr = [1,3,2,4,8,6,7,5];
function quick(arr) {
let len = arr.length;
if(len<=1) {
return arr
}
let midIndex = Math.floor(len/2);
let mid = arr.splice(midIndex,1);
let left=[],right=[];
for(let i=0;i<arr.length;i++) {
if(arr[i]>mid) {
right.push(arr[i]);
}else{
left.push(arr[i]);
}
}
return quick(left).concat(mid,quick(right))
}
console.log(quick(arr));// [1,2,3,4,5,6,7,8]
複製代碼