冒泡排序
function BubbleSort(arr){
for(let i = 0; i < arr.length-1; i++){
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
let temp = null
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
}
return arr
}
插入排序
function InsertSort(arr) {
let newArr = []
newArr.push(arr[0])
for (let i = 1; i < arr.length; i++) {
for(let j = newArr.length - 1; j >= 0; j--){
if (arr[i] > newArr[j]) {
newArr.splice(j + 1,0,arr[i])
break
}
if (j === 0) {
newArr.unshift(arr[i])
}
}
}
return newArr
}
快速排序
function QuickSort(arr) {
if (arr.length <= 1) {
return arr
}
var pointIndex = Math.floor(arr.length / 2)
var pointValue = arr.splice(pointIndex, 1)[0]
var leftArr = []
var rightArr = []
for(var i = 0; i <arr.length; i++){
var cur = arr[i]
cur > pointValue ? rightArr.push(cur) : leftArr.push(cur);
}
return QuickSort(leftArr).concat(pointValue, QuickSort(rightArr))
}
网友评论