标签:二路归并 ble i+1 ++ 算法 return quick highlight 快速排序
var arr = [‘General‘,‘Tom‘,‘Bob‘,‘John‘,‘Army‘]; var resArr = arr.sort(); console.log(resArr);//输出 ["Army", "Bob", "General", "John", "Tom"] var arr2 = [30,10,111,35,1899,50,45]; var resArr2 = arr2.sort(); console.log(resArr2);//输出 [10, 111, 1899, 30, 35, 45, 50]
var arr3 = [30,10,111,35,1899,50,45]; arr3.sort(function(a,b){ return a - b; }) console.log(arr3);//输出 [10, 30, 35, 45, 50, 111, 1899] var arr4 = [30,10,111,35,1899,50,45]; arr4.sort(function(a,b){ return b - a; }) console.log(arr4);//输出 [1899, 111, 50, 45, 35, 30, 10]
var arr5 = [{id:10},{id:5},{id:6},{id:9},{id:2},{id:3}]; arr5.sort(function(a,b){ return a.id - b.id }) console.log(arr5); //输出新的排序 // {id: 2} // {id: 3} // {id: 5} // {id: 6} // {id: 9} // {id: 10}
var arr6 = [{id:10,age:2},{id:5,age:4},{id:6,age:10},{id:9,age:6},{id:2,age:8},{id:10,age:9}]; arr6.sort(function(a,b){ if(a.id === b.id){//如果id相同,按照age的降序 return b.age - a.age }else{ return a.id - b.id } }) console.log(arr6); //输出新的排序 // {id: 2, age: 8} // {id: 5, age: 4} // {id: 6, age: 10} // {id: 9, age: 6} // {id: 10, age: 9} // {id: 10, age: 2}
//冒泡排序 function bubbleSort(arr){ var i = j = 0; for(i=1;i<arr.length;i++){ for(j=0;j<=arr.length-i;j++){ var temp = 0; if(arr[j]>arr[j+1]){ temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }
//快速排序 function quickSort(arr,l,r){ if(l < r){ var i = l, j = r, x = arr[i]; while(i<j){ while(i<j && arr[j]>x){ j--; if(i<j) //这里用i++,被换过来的必然比x小,赋值后直接让i自加,不用再比较,可以提高效率 arr[i++] = arr[j]; while(i<j && arr[i]<x){ i++; if(i<j){ //这里用j--,被换过来的必然比x大,赋值后直接让j自减,不用再比较,可以提高效率 arr[j--] = arr[i]; } } } arr[i] = x; quickSort(arr, l, i-1); quickSort(arr, i+1, r); } }
//将两个按值有序序列合并成一个按值有序序列,则称之为二路归并排序 function merge(left, right) { var result = [], il = 0, ir = 0; while (il < left.length && ir < right.length) { if (left[il] < right[ir]) { result.push(left[il++]); } else { result.push(right[ir++]); } } while(left[il]){ result.push(left[il++]); } while(right[ir]){ result.push(right[ir++]); } return result; }
标签:二路归并 ble i+1 ++ 算法 return quick highlight 快速排序
原文地址:https://www.cnblogs.com/jianguo221/p/11777280.html