functionArrayList(){this.array =[];
ArrayList.prototype.insert=function(item){this.array.push(item);};// 交换位置
ArrayList.prototype.swap=function(m, n){const temp =this.array[m];this.array[m]=this.array[n];this.array[n]= temp;};// 冒泡排序
ArrayList.prototype.bubbleSort=function(){const len =this.array.length;for(let j = len -1; j >=0; j--){for(let i =0; i < j; i++){if(this.array[i]>this.array[i +1]){this.swap(i, i +1);}}}};// 选择排序// https://www.bilibili.com/video/BV1yD4y127vy?p=142&spm_id_from=pageDriver
ArrayList.prototype.selectionSort=function(){const len =this.array.length;for(let j =0; j < length -1; j++){let min = j;for(let i = min +1; i < len; i++){if(this.array[min]>this.array[i]){
min = i;}}this.swap(min, j);}};// 插入排序// https://www.bilibili.com/video/BV1yD4y127vy?p=145&spm_id_from=pageDriver
ArrayList.prototype.insertionSort=function(){const len =this.array.length;for(let i =1; i < len; i++){const temp =this.array[i];let j = i;while(this.array[j -1]> temp && j >0){this.array[j]=this.array[j -1];
j--;}this.array[j]= temp;}};// 希尔排序// https://www.bilibili.com/video/BV1yD4y127vy?p=150&spm_id_from=pageDriver
ArrayList.prototype.shellSort=function(){const len =this.array.length;let gap = Math.floor(len /2);while(gap >=1){for(let i = gap; i < len; i++){const temp =this.array[i];let j = i;while(this.array[j - gap]> temp && j > gap -1){this.array[j]=this.array[j - gap];
j -= gap;}this.array[j]= temp;}
gap = Math.floor(gap /2);}};}
快速排序
//快速排序//1.选择枢纽constmedian=function(arr){//1.取出中间的位置const center = Math.floor(arr.length /2);const right = arr.length -1;const left =0;//2.判断大小并进行交换if(arr[left]> arr[center]){swap(arr, left, center);}if(arr[left]> arr[right]){swap(arr, left, right);}if(arr[center]> arr[right]){swap(arr, center, right);}//3.返回枢纽return center;};//2.快速排序// 这样会修改原数组,如果希望传入的原数组不改变 可以使用 QuickSort(arr.slice()) constQuickSort=function(arr){if(arr.length ==0){return[];}let center =median(arr);// 返回值是数组格式的const c = arr.splice(center,1)[0];const l =[];const r =[];for(let i =0; i < arr.length; i++){if(arr[i]< c){
l.push(arr[i]);}else{
r.push(arr[i]);}}returnQuickSort(l).concat(c,QuickSort(r));};