The average time complexity of the algorithm is O (nlogn ). However, when the input is an sorted array or an input in almost sorted order, the time complexity is O (n ^ 2 ). To solve this problem and ensure that the average time complexity is O (nlogn), A preprocessing step is introduced. The only purpose is to change the order of elements so that they can be sorted randomly. This preprocessing step can be run in O (n) time. Another simple method that can play the same role is to introduce a random element to the algorithm, which can be achieved by randomly selecting the principal component of the split element. The result of the random choice of the principal component relaxed all the steps on the input element arrangement with the same possibility. This step is introduced to correct the original fast sorting, and the Randomization fast sorting shown below can be obtained. The new algorithm is only in the range [low... In high], select an index v at random, exchange A [v] with A [low], and then continue with the original fast sorting algorithm. Here, parseInt (Math. random () * (high-low + 1) + low) returns a number between low and high.
Copy codeThe Code is as follows:
/*************************************** *
Algorithm: split
Input: array A [low... high]
Output:
1. If necessary, output the array A that is rearranged according to the preceding description;
2. Divide the new position w of element A [low;
****************************************/
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] in non-descending order
Rquicksort (A, 0, n-1 );
****************************************/
Function rquicksort (array, low, high ){
If (low /****** Randomize the principal component of the sharding element *******/
Var v = parseInt (Math. random () * (high-low + 1) + low );
Var tmp = array [low];
Array [low] = array [v];
Array [v] = tmp;
/****** Randomize the principal component of the sharding 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 );