let a =[1,6,4,33,9,7,2]
console.log(a.sort((a, b)=> a - b))
冒泡排序需要用到数字交换方法
// 交换方法1functionswap1(a,b){let c = a;
a = b;
b = a;}// 交换方法2functionswap2(a,b){[a,b]=[b,a]}// 交换方法3functionswap3(a,b){
a = a + b;
b = a - b;
a = a - b;}
冒泡排序
从数组第一项开始,每一项与下一项进行比较,如果大于下一项则互换位置,换完一轮则第一项是最小的一项
再从第二项开始比较,以此类推
因此一共需要比较数组长度-1轮,每轮需要比较数组长度-1再减去已比较轮数
// 实现数组中的数字交换functionswap(arr,i,j){
arr[i]= arr[i]+ arr[j];
arr[j]= arr[i]- arr[j];
arr[i]= arr[i]- arr[j];return arr;}// 冒泡排序
Array.prototype.bubble=functionbubble(){let that =this,
flag =false;for(let i =0; i < that.length -1; i++){for(let j =0; j < that.length -1- i; j++){if(that[j]> that[j +1]){swap(that, j, j +1);
flag =true;}}if(!flag)break;
flag =false;}return that;}let a =[1,6,4,33,9,7,2]
console.log(a.bubble())
插入排序
先将数组第一项插入新数组
再将数组每一项新数组中的每一项进行比较
如果大于则插入比较项之后,反之则插入比较项之前
// 冒泡排序
Array.prototype.insert=functioninsert(){let that =this,
arr =[];
arr.push(that[0]);for(let i =1; i < that.length; i++){letA= that[i];for(let j = that.length -1; j >=0; j--){letB= arr[j];if(A>B){
arr.splice(j +1,0,A);break;}if(j ===0){
arr.unshift(A)}}}return arr;}let a =[1,6,4,33,9,7,2]
console.log(a.insert())
快速排序(二分法)
找出中间项
每一项与中间项进行比较
如果大于中间项则插入存储大于中间项数值的数组,反之插入存储小于中间项数值的数组
将每个新数组都进行快速排序(递归)
最终将左中右三个数组或数值依次拼接
Array.prototype.quick=functionquick(){let that =this;if(that.length <=1){return that
}let middleIndex = Math.floor(that.length /2),
middleValue = that.splice(middleIndex,1)[0],
arrLeft =[],
arrRight =[];for(let i =0; i < that.length; i++){let num = that[i];
num < middleValue ? arrLeft.push(num): arrRight.push(num);}return quick.call(arrLeft).concat(middleValue, quick.call(arrRight));}let a =[1,6,4,33,9,7,2]
console.log(a.insert())