constbubbleSort=(arr)=>{const res =[...arr]for(let i =0; i < res.length -1; i +=1){for(let j =0; j < res.length -1- i; j +=1){if(res[j]> res[j +1]){const temp = res[j]
res[j]= res[j +1]
res[j +1]= temp
}}}return res
}
选择排序
找到数组中的最小值,选中它并将其放置在第一位
接着找到第二小的值,选中它并将其放置在第二位
以此类推,执行 n - 1 轮
constselectionSort=(arr)=>{const res =[...arr]for(let i =0; i < res.length -1; i +=1){let indexMin = i
for(let j = i; j < res.length; j +=1){if(res[j]< res[indexMin]){
indexMin = j
}}if(indexMin !== i){const temp = res[i]
res[i]= res[indexMin]
res[indexMin]= temp
}}return res
}
归并排序
分:把数组分成两半,再递归地对子数组进行“分”操作,直到分成一个个单独的数
合:把两个数合并为有序数组,再对有序数组进行合并,直到全部子数组合并为一个完整数组
constmergeSort=(arr)=>{constrec=(arr)=>{if(arr.length ===1)return arr
const mid = Math.floor(arr.length /2)const left = arr.slice(0, mid)const right = arr.slice(mid, arr.length)const orderLeft =rec(left)const orderRight =rec(right)const res =[]while(orderLeft.length || orderRight.length){if(orderLeft.length && orderRight.length){
res.push(orderLeft[0]< orderRight[0]? orderLeft.shift(): orderRight.shift())}elseif(orderLeft.length){
res.push(orderLeft.shift())}elseif(orderRight.length){
res.push(orderRight.shift())}}return res
}returnrec(arr)}
快速排序
分区:从数组中任意选择一个“基准”,所有比基准小的元素放在基准前面,比基准大的元素放在后面
递归:递归地对基准前后的子数组进行分区
constquickSort=(arr)=>{constrec=(arr)=>{if(arr.length ===1)return arr
const left =[]const right =[]const mid = arr[0]for(let i =1; i < arr.length; i +=1){if(arr[i]< mid){
left.push(arr[i])}else{
right.push(arr[i])}}return[...rec(left), mid,...rec(right)]}returnrec(arr)}
顺序搜索
遍历数组,找到跟目标值相等的元素,就返回它的下标
遍历结束后,如果没有搜索到目标值,就返回 -1
Array.prototype.sequentialSearch=function(item){for(let i =0; i <this.length; i +=1){if(this[i]=== item)return i
}return-1}const res =[1,2,3,4,5].sequentialSearch(0)
二分搜索
前提:数组是有序数组
从数组的中间元素开始,如果中间元素正好是目标值,则搜索结束
如果目标值大于或小于中间元素,则在大于或小于中间元素的那一半数组中搜索
Array.prototype.binarySearch=function(item){let low =0let high =this.length -1while(low <= high){const mid = Math.floor((low + high)/2)const element =this[mid]if(element < item){
low = mid +1}elseif(element > item){
high = mid -1}else{return mid
}}return-1}const res =[1,2,3,4,5].binarySearch(0)