下面是自己实现的一个排序方法的学习记录,不过我估计我的这种实现方式必定是有其他人也实现过,毕竟关于数组排序算法网上就多达10来种的方案(ps:然后自己也懒得去看,就自己实现了下)
也希望有缘人看到这段代码能够指正一下或者哪里是否可再优化一下的~
二分排序法(起着玩的,不喜勿喷)
思路:主要是通过2等分一段索引区间逐渐搜小元素的比较范围,好处就是比冒泡排序逐个双for遍历要快10倍甚至更多(如果数组长度较短的话没什么区别,主要体现在长数组,比如长度几百甚至上千)
function sortBy(arr, type) {
const resultArr = arr.reduce(function (arr, curVal){
_baseSort(curVal, arr, 0, arr.length - 1)
return arr
}, [])
return type === 'desc' ? resultArr.reverse() : resultArr
}
function _baseSort(val, arr, startIndex, endIndex) {
if (arr.length === 0) {
arr.push(val)
return
}
// 取索引段的差值
const diffCount = endIndex - startIndex
switch(diffCount) {
case 0:
if (arr[0] >= val) {
arr.splice(startIndex, 0, val)
} else {
arr.splice(endIndex + 1, 0, val)
}
break
case 1:
if (arr[startIndex] >= val) {
arr.splice(startIndex, 0, val)
} else {
if (arr[endIndex] >= val) {
arr.splice(endIndex, 0, val)
} else {
arr.splice(endIndex + 1, 0, val)
}
}
break
default:
// 2等分索引区间的差值,再以(startIndex + middleNum)的索引值(作为中轴线)和val进行递归判断
// 逐渐缩小判断的区间,计算速度是冒泡排序的10倍(短数组基本不会有差别,但是如果是长度几百或更长就能够体现出来)
const middleNum = Math.floor(diffCount / 2)
if (arr[startIndex + middleNum] > val) {
_baseSort(val, arr, startIndex, startIndex + middleNum)
} else if (arr[startIndex + middleNum] === val) {
arr.splice(startIndex + middleNum, 0, val)
} else {
_baseSort(val, arr, startIndex + middleNum, endIndex)
}
break
}
}
普通冒泡排序:
var t1 = 0
function bubbleSort(arr) {
t1 = new Date().valueOf() // 测试
let length = arr.length;
if (!length) {
return [];
}
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
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7, 4, 5, 8, 9, 0, 2, 3, 6, 7, 4, 5, 8, 9, 0, 6, 7, 4, 5, 8, 9, 0, 2, 3, 6, 7, 4, 5, 8, 9, 0, 6, 7, 4, 5, 8, 9, 0, 2, 3, 6, 7, 4, 5, 8, 9, 0, 6, 7, 4, 5, 8, 9, 0, 2, 3, 6, 7, 4, 5, 8, 9, 0, 6, 7, 4, 5, 8, 9, 0, 2, 3, 6, 7, 4, 5, 8, 9, 0, 6, 7, 4, 5, 8, 9, 0, 2, 3, 6, 7, 4, 5, 8, 9, 0]
var arr2 = sortBy(arr)
console.log(arr2.length) // 770
console.log(new Date().valueOf() - t2) // 3
console.log('=============')
var arr3 = bubbleSort(arr)
console.log(arr3.length) // 770
console.log(new Date().valueOf() - t1) // 12
结果可看出从时间上比冒泡要快很多