This article describes the JS implementation of the random quick sort of instance code, the need for friends can refer to
The average time complexity of the algorithm is O (NLOGN). But when the input is an array that has already been sorted, or an almost orderly input, the time complexity is O (n^2). To solve this problem and to ensure that the average time complexity is O (NLOGN) is to introduce preprocessing steps, its sole purpose is to change the order of elements to make it randomly sorted. This preprocessing step can be run in O (n) time. Another simple way to do this is to introduce a random element into the algorithm, which can be achieved by randomly selecting the main element of the split element. The result of randomly selecting a primary element relaxes the same procedure for all permutations of the INPUT element. This step is introduced to correct the original quick sort, and the randomization can be sorted as shown below. The new algorithm simply selects an index v uniformly and randomly in the interval [Low...high] and swaps the a[v] and A[low], then continues with the original quick sort algorithm. Here, parseint (Math.random () * (high-low+1) + low) returns a number between low and high.
Copy Code code as follows:
/****************************************
algorithm: Split
Input: array A[low...high]
Output:
1. If necessary, Outputs a rearrangement of the array as described above;
2. Dividing the new position of the element A[low] W;
****************************************/
Function split (array, low, high) {
var i = low;
var x = array[l OW];
for (var j = low + 1; J <= High; j + +) {
if (Array[j] <= x) {
i + +;
if (i!= j) {
var temp = array[ I];
Array[i] = array[j];
Array[j] = temp;
}
}
}
temp = Array[low];
Array[low] = array[i];
Array[i] = temp;
return i;
}
/****************************************
Algorithm: Rquicksort
Input: a[0...n-1]
Output: Array in non-descending order A[0...n-1]
Rquicksort (A, 0, n-1);
****************************************/
Function Rquicksort (array, low, high) {
if (Low < high) {
/* Randomization of the primary element of the split element *******/
var v = parseint (Math.random () * (high-low+1) + low);
var tmp = Array[low];
Array[low] = ARRAY[V];
Array[v] = tmp;
/****** The primary *******/
var of the randomization split elementW = Split (array, low, high);
Rquicksort (array, low, w-1);
Rquicksort (Array, w +1, High);
return array;
}
}
var array = [0, a, MB, n,];
Array = rquicksort (array,, array.length-1);
Console.log (A Rray);