Quick Sort JS Code implementation
The idea of "quick sorting" is simple, and the entire sequencing process takes only three steps:
(1) In the dataset, select an element as the "datum" (pivot).
(2) All elements smaller than "datum" are moved to the left of "datum", and all elements that are greater than "datum" are moved to the right of "datum".
(3) for the two subsets to the left and right of the Datum, repeat the first and second steps until there is only one element left in all the subsets.
functionQuickSort (arr) {//Check the number of elements in the array, if it is less than or equal to 1, returns if(Arr.length <= 1) { returnarr; } //Select Intermediate element as "datum" (pivot) varPivotindex = Math.floor (ARR.LENGTH/2);varPivot = Arr.splice (pivotindex,1) [0];//Splice Returns the deleted item from the original array (no empty array returned) varleft = []; varright = []; //start traversing array, elements less than "datum" are placed on the left subset, elements greater than datum are placed on the right subset for(vari=0; i<arr.length; i++){ if(arr[i]<pivot) {Left.push (arr[i]); }Else{Right.push (arr[i]); } } //Recursive varNEWARR = []; NEWARR=QuickSort (left). Concat ([pivot], QuickSort (right)); returnNEWARR;} Console.log (QuickSort ([85,24,63,45,17,17,31,96,50,8]));//[8, +, +, +,----
There are many methods for selecting datum values, and choosing different datum values will affect the efficiency of sorting, so select the appropriate datum pivot for the actual application.
The sort () method in JavaScript
1. After the array calls the sort method, it affects itself (rather than generating a new array)
The 2.sort () method is sorted by character by default, so when sorting a numeric array, you can't take it for granted that it will be sorted by number size!
3. To change the default sort behavior (that is, sort by character), you can specify the collation function yourself
function Compare (value1,value2) { return value1- value2;} var arr1 = [85,24,63,45,17,17,31,96,50,8];arr1.sort (); Console.log (arr1); // [+, + , 8 ,----- Arr1.sort (Compare); Console.log (arr1); // [8, +, +, +,----
JavaScript implementation for quick Sort (QuickSort)