- function Quicksort (arr) {
- function Q (start,end) {
- if (start>=end) {return;}
- var pivot = start,
- temp = Arr[pivot],
- i = start+1;
- for (; i<=end;i++) {
- if (arr[i]<temp) {
- var s = arr.splice (i,1) [0];
- Arr.splice (start,0,s);
- pivot++;
- }
- }
- Q (start,pivot-1);
- Q (pivot+1,end);
- }
- Q (0,arr.length);
- return arr;
- }
- var arrs = [9,45,45,90,3,77,4,90];
- var c = quicksort (ARRS);
- Console.log (c);
if (start>=end) {return;} in line 3rd, I consider this way of quitting recursion.
When there are two items left in the Subarray, two scenarios are analyzed:
(1) When the first sub-array (passed to the parameter start) is smaller than the second item (passed to the parameter end)
In the function q the first adjustment is made, the last variable start points to the first item, the variable pivot points to the first item, and then:
Q (start,pivot-1);//At this time Start==pivot, so start>pivot-1, through if (start>=end) {return;} Exit recursion
Q (pivot+1,end);//At this time pivot+1==end, the same as exit recursion
(2) When the first item is larger than the second
In function q, make the adjustment again, the last variable start points to the first item, the variable pivot points to the second item, and then:
Q (start,pivot-1);//start==pivot-1 at this time, exit recursion
Q (pivot+1,end);//At this time pivot+1>end; also exits recursion
Fast Sort algorithm JavaScript implementation