在面试中高级前端常常会被问道前端的算法,今天我们就来聊下前端那几个算法。
常见的几种算法
- 快速排序
- 插入排序
- 冒泡排序
快速排序
快速排序的思路就是取数组的中间值,并分为左右两个数组进行递归排序,直到左右都排序完成。
const quickSort = arr => {
if (!arr.length) return
const MEDIANINDEX = Math.floor(arr.length/2)
const MEDIAN = arr.splice(MEDIANINDEX,1)[0]
let left=[],right=[]
arr.map((item, index) => {
if(item > MEDIAN) {
right.push(item)
} else {
left.push(item)
}
})
return [...quickSort(left), ...[MEDIAN], ...quickSort(right)]
}
quickSort([3,5,8,6,3,2,9,1,10])
插入排序
插入排序的思路主要把数组分成有序,无序两个数组。然后不断将无序的第一个元素按大小顺序插入到有序中去,最终将所有无序区元素都移动到有序完成排序
const insertionSort = arr => {
let preIndex, current;
for (var i = 1; i < arr.length; i++) {
preIndex = i - 1;
current = arr[i];
while(preIndex >= 0 && arr[preIndex] > current) {
arr[preIndex+1] = arr[preIndex];
preIndex--;
}
arr[preIndex+1] = current;
}
return arr;
}
insertionSort([3,5,8,6,3,2,9,1,10])
冒泡排序
比较数组两个相邻的元素,如果第一个比第二个大,就交换他们两个。以此类推
const bubbleSort = arr => {
if (!arr.length == 0) return arr
for (var i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
}
}
}
return arr
}
bubbleSort([2,5,7,9,2,5,4])