let arrayList = [1,4,3,2,6,5]
/**
* 快速排序
*
* */
function quickSort (arrayList){
let copyArrayList = [...arrayList]
if (copyArrayList.length < 2 )return copyArrayList
let povit = copyArrayList[0]
let smallArrayList = []
let bigArrayList = []
for (let i = 1;i<copyArrayList.length;i++){
if (copyArrayList[i] < povit){
smallArrayList.push(copyArrayList[i])
}else {
bigArrayList.push(copyArrayList[i])
}
}
return [...quickSort(smallArrayList),povit,...quickSort(bigArrayList)]
}
console.log('快速排序',quickSort(arrayList))
/**
*
* 冒泡排序
* 首先每一位一次顺序对比 找到最大数移到最后一位
* 重复上面步骤
* 改进方法 再次循环时候可以不计数前面的已经排序过的 i < bubbingArrayList.length - j - 1
*
* */
let bubbingArrayList = [1,4,3,2,6,5]
function bubbingSort (bubbingArrayList){
for (let j = 0;j<bubbingArrayList.length;j++) {
for(let i = 0;i<bubbingArrayList.length;i++) {
if (bubbingArrayList[i] > bubbingArrayList[i+1]) {
let temp = bubbingArrayList[i]
bubbingArrayList[i] = bubbingArrayList[i+1]
bubbingArrayList[i+1] = temp
}
}
}
return bubbingArrayList
}
console.log('冒泡排序',bubbingSort(bubbingArrayList))
/**
*
* 选择排序
*
* */
let selectArrayList = [1,4,3,2,6,5]
function selectSort (selectArrayList){
for (let i = 0;i<selectArrayList.length;i++ ){
let minIndex = i
for (let j = i + 1 ;j<selectArrayList.length;j++){
if(selectArrayList[j] < selectArrayList[minIndex]) {
minIndex = j
}
}
let temp = selectArrayList[i]
selectArrayList[i] = selectArrayList[minIndex]
selectArrayList[minIndex] = temp
}
return selectArrayList
}
console.log('选择排序',selectSort(selectArrayList))
/**
* 插入排序
* */
let insertArrayList = [1,4,3,2,6,5]
function insertSort (insertArrayList){
for(let i = 1;i<insertArrayList.length;i++){
let leftIndex = i - 1
let temp = insertArrayList[i]
while (leftIndex >= 0 && insertArrayList[leftIndex] > temp) {
insertArrayList[leftIndex + 1] = insertArrayList[leftIndex]
leftIndex--
}
insertArrayList[leftIndex + 1] = temp
}
return insertArrayList
}
console.log('插入排序',insertSort(insertArrayList))
JS排序算法(冒泡排序、快速排序、插入排序、选择排序)
最新推荐文章于 2024-08-12 19:27:52 发布