Function Quicksort (ARR ){ // If the array has only one number, it will be returned directly; If (ARR. Length <1 ){ Return Arr ;} // Locate the index value of the number in the middle; if it is a floating point, it is rounded down. VaR Centerindex = math. Floor (ARR. Length/2 ); // Locate the value of this number based on the index value of the intermediate number; VaR Centernum = arr. splice (centerindex, 1 ); // Left-side storage VaR Arrleft = []; // Number of items 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 = [, 27 ]; VaR Arr1 = Quicksort (arrsort); console. Log (arr1 );
The first phase of Video Teaching in "Wonderful classroom.
The main principle is: the principle of fast sorting: Find the benchmark, create two Arrays for storage, recursive
Benchmark: Find a number in the middle of the array;
Create two Arrays for storage: use this benchmark to store the left and right values in two new arrays defined respectively;
Recursion: Calls itself within a function;
Here I sum up the following:
1. A judgment is required and a value is returned; otherwise, it is an endless loop;
2. When you call yourself internally, the passed parameter is a variable defined internally. This variable is associated with the parameter obtained during initial transmission;
3. recursion can be used to perform the same job;
This is the first variable to execute the function: the number in the middle is 40; the condition smaller than 40 in the loop is stored in arrleft, and the value greater than 40 is stored in arrright. For example
Second function call
When return quicksort (arrleft). Concat (centernum, quicksort (arrright) is executed ));
Quicksort (arrleft) will call the function. The passed parameters are [, 27].
The number in the middle is 2. If the number is smaller than 2, the left arrleft is put. If the number is greater than 2, the right arrright is put.
Finally, call quicksort (arrright)
You can call yourself in the same loop. If the length of the input parameter is smaller than 1, the input parameter is returned.