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.
For example, there is now a dataset {85, 24, 63, 45, 17, 31, 96, 50}, how to sort it?
The first step is to select the middle element 45 as the "datum". (the base value can be arbitrarily selected, but selecting the middle value is easier to understand.) )
In the second step, each element is compared with "datum" in order to form two subsets, one "less than 45" and another "greater than or equal to 45".
The third step is to repeat the first and second steps for two subsets until only one element is left in all the subsets.
The following is a reference to the online information (here and here), using the JavaScript language to implement the above algorithm.
First, define a quicksort function whose arguments are an array.
var quickSort = function (arr) {
};
Then, the number of elements in the array is checked and returned if it is less than or equal to 1.
var quickSort = function (arr) {
if (arr.length <= 1) {return arr;}
};
Next, select Datum (pivot) and detach it from the original array, and then define two empty arrays to hold two subsets of the left and right.
var quickSort = function (arr) {
if (arr.length <= 1) {return arr;}
var pivotindex = Math.floor (ARR.LENGTH/2);
var pivot = Arr.splice (pivotindex, 1) [0];
var left = [];
var right = [];
};
Then, start iterating over the array, the elements that are smaller than the "datum" are placed on the left subset, and the elements greater than the datum are placed on the right subset.
var quickSort = function (arr) {
if (arr.length <= 1) {return arr;}
var pivotindex = Math.floor (ARR.LENGTH/2);
var pivot = Arr.splice (pivotindex, 1) [0];
var left = [];
var right = [];
for (var i = 0; i < arr.length; i++) {
if (Arr[i] < pivot) {
Left.push (Arr[i]);
} else {
Right.push (Arr[i]);
}
}
};
Finally, using recursion to repeat the process, you can get the sorted array.
var quickSort = function (arr) {
if (arr.length <= 1) {return arr;}
var pivotindex = Math.floor (ARR.LENGTH/2);
var pivot = Arr.splice (pivotindex, 1) [0];
var left = [];
var right = [];
for (var i = 0; i < arr.length; i++) {
if (Arr[i] < pivot) {
Left.push (Arr[i]);
} else {
Right.push (Arr[i]);
}
}
Return QuickSort (left). Concat ([pivot], QuickSort (right));
};
When used, call Quicksort () directly.
Excerpt from: Nanyi blog
JavaScript Quick Sort (Quicksort)