Core code:
Copy Code code as follows:
function QuickSort (arr) {
If the array has only one number, it returns directly;
if (arr.length<1) {
return arr;
}
Find the index value of that number in the middle, and if it's a float, take it down.
var centerindex = Math.floor (ARR.LENGTH/2);
The value of this number is found according to the index value of the middle number;
var centernum = Arr.splice (centerindex,1);
Store the number on the left
var arrleft = [];
The number on the right
var arrright = [];
for (i=0;i<arr.length;i++) {
if (arr[i]<centernum) {
Arrleft.push (Arr[i])
}else if (arr[i]>centernum) {
Arrright.push (Arr[i])
}
}
Return QuickSort (Arrleft). Concat (Centernum,quicksort (arrright));
};
var arrsort = [33,18,2,40,16,63,27];
var arr1 = QuickSort (Arrsort);
Console.log (ARR1);
The main principle is: the principle of rapid sorting: Find the datum point, create two arrays to store, and recursively
Datum point: Is to find a number in the middle of this array;
Set up two arrays to store separately: that is, with this datum point, its left and right values are stored in the two defined new array;
Recursion: Calling itself inside a function;
The point I'm summarizing here is when using recursion:
1. Must have a judgment and return a value; otherwise, it's a dead loop.
2. In the internal call itself, the passing of the parameter is an internal definition of a variable, this variable and the initial transmission of parameters, associated;
3. To perform the same work, consideration may be given to the use of recursion;
This is the first time a variable of a function is executed: The median is 40, and according to the judgment condition of the cycle less than 40 is stored in Arrleft, more than 40 of which is stored in arrright. The following figure
Second Call function
, when executed to return QuickSort (Arrleft). Concat (Centernum,quicksort (arrright));
QuickSort (Arrleft) will call the function, and the arguments passed are [33,18,2,16,27]
The median is 2, lower than 2 small left arrleft, 2 larger than the right arrright
Finally go to call Quicksort (Arrright)
The loop calls itself back, until the passed parameter length, less than 1, returns the incoming argument.