Quick sort with bubbling sort, is a kind of exchange sort. The quick sort is a sort of division exchange proposed by C.r.a.hoare in 1962. It adopts a strategy of division, which is usually referred to as the Division method (Divide-and-conquermethod). The time complexity of quick sorting is O (Nlogn), which is much faster than other O (n^2) sorting algorithms, but it is still difficult to achieve.
The basic idea of divide-and-conquer method is: to decompose the original problem into several sub-problems with smaller size but similar structure to the original problem. Solve these sub-problems recursively, then combine the solutions of these sub-problems into the solution of the original problem.
Basic Idea :
Quick sort uses the idea of dividing and ruling, taking an element from the sequence to be sorted as a benchmark, dividing the ordered sequence into left and right two sub-sequences, and making the elements on the left side of the datum smaller than the Datum elements, the elements on the right are greater than or equal to the datum elements, so that the position of the datum element is correct. The sort can then be done by recursively doing the same for each subsequence.
key points of implementation :
The difficulty of the implementation is how to move the remaining elements to the sides of the datum by size, after selecting a datum. Here is an O (1) Approach to spatial complexity:
The following is an example of a set of elements to be sorted (data), a simple description of the process of dividing a sequence into two parts
| 0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
| 72 |
38 |
54 |
87 |
96 |
17 |
57 |
84 |
25 |
91 |
First we take data[0] as a benchmark, save data[0 with a variable temp, and then move all elements less than temp to the head of the sequence, elements greater than or equal to temp move to the end of the sequence, record the sequence head and tail with i=0,j=n-1, and then traverse from J. Data[j]>=temp do not make any exchanges, while J –, continue to compare next, if DATA[J] is less than temp, then data[j] and Data[i] are exchanged, then i++, and compare data[i] with temp,data[i] less than temp, Then do not do any exchange, at the same time i++, continue to compare the next, if Data[i]>=temp, then will data[i] and Data[j] Exchange, J –, and then compare data[i] and temp. From the description can be found, first we start from the tail, if an exchange occurs, switch to the head, then the exchange and then cut back, so the exchange, until the I=j, the final position of I is the first selection of the base element position. This sort of order is done, and then recursively sorts the subsequence, where it is necessary to judge if there is no subsequence to the left of the final datum position without having to recursively sort the left subsequence, and if there is no subsequence to the right of the datum position, the right subsequence does not need to be recursively sorted.
Java implementations :
PackageCom.vicky.sort;ImportJava.util.Random;/** * Exchange Sort: quick Sort * * Time complexity: O (NLOGN) * * @author Vicky * */ Public class QuickSort { Public Static<t extends Comparable<t>>void Sort(t[] data) {LongStart = System.nanotime ();if(NULL= = data) {Throw NewNullPointerException ("Data"); }if(Data.length = =1) {return; } devidesort (Data,0, Data.length-1); System.out.println ("Use time:"+ (System.nanotime ()-start)/1000000); }Private Static<t extends Comparable<t>>void Devidesort(t[] Data,intStartintEnd) {inti = start;intj = END; T temp = Data[start];BooleanDirect =false; while(I < J) {if(direct) {if(Data[i].compareto (temp) >=0) {Sortutils.swap (data, I, j); j--; Direct =false; }Else{i++; } }Else{if(Data[j].compareto (temp) <0) {Sortutils.swap (data, I, j); i++; Direct =true; }Else{j--; } } }if(Start < I-1) {Devidesort (data, start, I-1); }if(i +1< end) {Devidesort (data, i +1, end); } } Public Static void Main(string[] args) {Random ran =NewRandom (); integer[] data =Newinteger[2]; for(inti =0; i < data.length; i++) {Data[i] = Ran.nextint (10000); } quicksort.sort (data); Sortutils.printarray (data); }}
Efficiency Analysis :
(1) Complexity of time
O (NLOGN)
(1) Worst time complexity
The worst-case scenario is that each time the selected datum is the smallest (or largest) record of the keyword in the current unordered region, the result is that the sub-interval to the left of the Datum is empty (or the right sub-interval is empty), and the number of records in another non-empty sub-interval is divided by only one less than the number of records Therefore, the fast sorting must do N-1 division, the first Division of the beginning of the interval length of n-i+1, the required number of comparisons is N-i (1≤i≤n-1), the total number of comparisons reached the maximum value:Cmax = N (n-1)/2=o (n2)。 If the partitioning algorithm given above, each time the current unordered area of the 1th record as the benchmark, then when the file's record has been in an ascending order (or descending order), each partition is taken by the baseline is the current unordered region of the minimum (or maximum) of the record, the fast sort will require the most number of comparisons.
(2) Best time complexity
In the best case, the datum for each partition is the "median" record of the current unordered region, and the result is that the length of the two unordered sub-ranges of the datum is roughly equal to the left and right. Total number of keywords compared: 0 (NLGN).
Note: It is easier to use recursive trees to analyze the best case comparisons. Because the left and right sub-interval length is roughly equal after each division, so the height of the recursive tree is O (LGN), and the recursive tree each layer on each node corresponding to the division of the number of key words required in the process of the sum of the total number of keys not more than N, so the overall ordering process required to compare the overall frequency of C ( Because fast-sorting records move no more than the number of comparisons, the worst-case complexity for fast sorting should be 0 (N2) and the best time complexity is O (NLGN).
(3) Selection of benchmark keywords
Selecting the Divided datum keywords in the current unordered area is the key to determining the performance of the algorithm.
① the rules of "three taking in"
The "three take in" rule, that is, in the current interval, the first, the end of the interval and the middle position of the keyword comparison, take the values of the three corresponding records as a benchmark, before the beginning of the division of the benchmark record and the 1th record of the area to exchange, thereafter the division process and the above given partition algorithm exactly the same.
② random number K (Low≤k≤high) between low and high, using r[k] as the benchmark
The best way to select a datum is to use a random function to generate a random number K (Low≤k≤high) between low and high, using r[k] as the benchmark, which is equivalent to forcing the R[low. The records in high] are randomly distributed. The quick sort obtained by this method is generally called a random quick sort.
Note: A randomized quick sort is very different from a general fast sorting algorithm. However, after randomization, the performance of the algorithm is greatly improved, especially for the initial order of the file, it is generally not possible to cause the worst case occurrence. The randomization of the algorithm is not only suitable for fast sequencing, but also for other algorithms that require random distribution of data.
(4) Average time complexity
Although the worst time for fast sorting is O (N2), in terms of average performance, it is the fastest in the internal sorting algorithm based on the keyword comparison, and hence the name of the fast sort. Its average time complexity is O (NLGN).
(2) Complexity of space
O (LGN)
Quick sort requires a stack within the system to implement recursion. If each partition is more uniform, the height of its recursive tree is O (LGN), so the stack space after recursion is O (LGN). In the worst case, the height of the recursive tree is O (n), and the required stack space is O (n).
(3) Stability
Not stable
The stability of a quick sort is related to how it chooses the benchmark and if it is exchanged.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Sorting algorithm Series--Quick sort