function quick_sort(arr,i,j){
var left = i; //哨兵i
var right = j; //哨兵j
var key = arr[i]; //标准值
if(i<j){
while(i < j){
while(arr[j] >= key && i < j) j--;
if(i<j) arr[i++] = arr[j];
while(arr[i] <= key && i < j) i++;
if(i < j) arr[j--] =arr[i];
}
arr[i] = key;
quick_sort(arr,left,i-1);
quick_sort(arr,i+1,right);
}
}
var arr = [3,3,-5,6,0,2,-1,-1,3];
quick_sort(arr,0,arr.length-1);
console.log(arr);
冒泡排序
function fn(arr){
for(let i=0;i<arr.length;i++){
for(let j=0;j<arr.length-1-i;j++){
if(arr[j]>arr[j+1]){
let temp = arr[j+1];
arr[j+1]=arr[j];
arr[j]=temp;
}
}
}
}
var arr = [3,3,-5,6,0,2,-1,-1,3];
fn(arr);
console.log(arr);
归并排序
function mergeSort(arr){
let len = arr.length;
if(len <2) return arr;
let mid = Math.floor(len/2);
//拆分为两个子数组
let left = arr.slice(0,mid);
let right = arr.slice(mid,len);
//递归拆分
let mergeSortLeft = mergeSort(left);
let mergeSortRight = mergeSort(right);
//合并
return merge(mergeSortLeft ,mergeSortRight );
}
function merge(left,right){
let result =[];
while(left.length &&right.length){
if(left[0]<=right[0]){
result.push(left.shfit());
}else{
result.push(right.shfit());
}
}
while(left.length) result.push(left.shfit());
while(right.length) result.push(right.shfit());
return result;
}