之前写的排序总结一遍. 大部分来源js算法那本书
- 之前写的排序总结一遍. 大部分来源js算法那本书
- 还有一个堆排序没传, 那个可得细细的写
二分查找
function bianryList(arr, item) {
var low = 0
var heigh = arr.length - 1
while (low <= heigh) {
var mid = Math.floor((low + heigh)/2)
var temp = arr[mid]
if (temp === item) return mid
if (temp > item) {
heigh = mid - 1
} else {
low = mid + 1
}
debugger
}
return null
}
var arr = [1,2,3,5,6,9,12,15]
var res = bianryList(arr, 15)
debugger;
冒泡排序
function maopao(arra) {
var temp;
let count = 0
for (var i = 0; i < arra.length-1; i++) { //比较多少趟,从第一趟开始
for (var j = 0; j < arra.length - i - 1; j++) { //每一趟比较多少次数
count++
if (arra[j] > arra[j + 1]) {
temp = arra[j];
arra[j] = arra[j + 1];
arra[j + 1] = temp;
}
}
};
console.log(count)
return arra;
}
var arrry = [85, 24, 63, 17, 31, 17, 86, 50];
var s = maopao(arrry);
debugger
插入排序
function insertionSort(array) {
var length = array.length,
j, temp;
for (var i = 1; i < length; i++) {
j = i;
temp = array[i];
while (j > 0 && array[j - 1] > temp) {
array[j] = array[j - 1];
j--;
}
array[j] = temp;
};
}
var arr = [3, 5, 1, 4, 2, 6]
insertionSort(arr)
debugger
归并排序
function mergeSort(arr) {
var len = arr.length
if (len < 2) {
return arr
}
var mid = Math.floor(len / 2)
var left = arr.slice(0, mid)
var right = arr.slice(mid, len)
return merge(mergeSort(left), mergeSort(right))
}
function merge(left, right) {
var reslut = []
var li = 0
var ri = 0
while (li < left.length && ri < right.length) {
if (left[li] > right[ri]) {
reslut.push(right[ri++])
} else {
reslut.push(left[li++])
}
}
while (li < left.length) {
reslut.push(left[li++])
}
while (ri < right.length) {
reslut.push(right[ri++])
}
return reslut
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
mergeSort(arr)
debugger
快速排序
function quickArr(arr) {
var len = arr.length
if (len < 2) {
return arr
}
debugger
var temp = arr[0]
var left = []
var right = []
arr.forEach((val, index, arr) => {
if (index === 0) {
return
}
if (val < temp) {
left.push(val)
} else {
right.push(val)
}
})
// return Array.prototype.concat(quickArr(left), temp, quickArr(right))
return quickArr(left).concat(temp, quickArr(right))
}
var arr = [1, 3, 4, 2, 5, 6]
var res = console.log(quickArr(arr))
console.log(arr)
debugger;