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.
/****************************************
Algorithm: Split
Input: Array A[low...high]
Output:
1. If necessary, output the rearranged array a 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[low];
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 a[0...n-1 by non-descending order]
Rquicksort (A, 0, n-1);
****************************************/
function Rquicksort (array, low, high) {
if (Low < high) {
/****** the primary element *******/of the random split element
var v = parseint (Math.random () * (high-low+1) + low);
var tmp = Array[low];
Array[low] = Array[v];
ARRAY[V] = tmp;
/****** the primary element *******/of the random split element
var w = split (array, low, high);
Rquicksort (array, low, w-1);
Rquicksort (Array, w +1, High);
return array;
}
}
var array = [33, 22, 11, 88, 23, 32];
Array = rquicksort (array, 0, array.length-1);
Console.log (array);