Quick sorting and optimization (Java Edition)

Source: Internet
Author: User

Quick sorting and optimization (Java Edition)

Quicksort is an improvement in Bubble sorting. Quick sorting was proposed by C. A. R. Hoare in 1962.

Detailed process of a quick sort:
Select the first value of the array as the pivot value.

Code implementation:
Package QuickSort; public class QuickSortRealize {public static void QuickSort (int [] arr) {QSort (arr, 0, arr. length-1);} // sort the subsequences of the ordered table quickly. The minimum and maximum values of the subsequences to be sorted are low and high public static void QSort (int [] arr, int low, int high) {int lower; if (low
  
   
= Arr. length) {new Exception ();} int foreign tkey; Foreign tkey = arr [low]; // select the first record as the pivot record while (low
   
    
= Pivotkey) {// if it is greater than the pivot value, the subscript is reduced by one. Otherwise, the loop jumps out. High --;} Swap (arr, low, high); // exchange while (low
    
   
  

Time Performance of quick sortingDepending on the depth of the Quick Sort recursion, the number of recursion can be used to describe the execution of the algorithm. If the recursive tree is balanced, the performance at this time is also the best.
That is to say, in the optimal condition, the time complexity of the fast sorting algorithm is O (nlogn ).

In terms of space complexity, the main reason is the use of stack space caused by recursion. In the best case, the depth of the recursive tree is log2n, and the space complexity is O (logn). In the worst case, recursive call is required. The space complexity is O (n), and the average space complexity is also (logn ).
Unfortunately, the comparison and exchange of keywords are skipped, so fast sorting is unstable.
Sorting method.

Optimization Algorithm: 1. Pivot of Optimization Selection

In the three-digit fetch, the three keywords are sorted first, and the intermediate number is used as the pivot. Generally, the numbers are left, right, and middle, and can be randomly selected.
For a very large sequence to be sorted, it is still not enough to ensure that a good pivo tkey can be selected. Therefore, there is another way to take three samples from the array in the so-called nine-number fetch, take three numbers each time, three samples each take out the number, and then take one of the three numbers as the pivot.

Package QuickSort; public class QuickSortRealize {public static void QuickSort (int [] arr) {QSort (arr, 0, arr. length-1);} // sort the subsequences of the ordered table quickly. The minimum and maximum values of the subsequences to be sorted are low and high public static void QSort (int [] arr, int low, int high) {int lower; if (low  = Arr. length) {new Exception ();} int pivotkey; ChoosePivotkey (arr, low, high); // select the pivot value pivotkey = arr [low]; while (low  = Pivotkey) {// if it is greater than the pivot value, the subscript is reduced by one. Otherwise, the loop jumps out. High --;} Swap (arr, low, high); // exchange while (low  Arr [high]) {// ensure that the left side is smaller than Swap (arr, low, high);} if (arr [mid]> arr [high]) {// ensure that Swap (arr, mid, high) is smaller in the middle;} // The maximum value is in the rightmost if (arr [mid]> arr [low]) {// Swap (arr, mid, low);} public static void main (String [] args) {int [] arr = {50, 10, 90, 30, 70, 40, 80, 60, 20}; QuickSort (arr); for (int array: arr) {System. out. print (array + "");} System. out. println ();}}   
2. Optimize unnecessary exchanges

Package QuickSort; public class QuickSortRealize3 {public static void QuickSort (int [] arr) {QSort (arr, 0, arr. length-1);} // sort the subsequences of the ordered table quickly. The minimum and maximum values of the subsequences to be sorted are low and high public static void QSort (int [] arr, int low, int high) {int lower; if (low  = Arr. length) {new Exception () ;}int foreign tkey; Foreign tkey = arr [low]; // select the first record as the pivot record int tempCopy = foreign tkey; // back up the pivot value to tempCopy while (low  = Pivotkey) {// if it is greater than the pivot value, the subscript is reduced by one. Otherwise, the loop jumps out. High --;} // Swap (arr, low, high); // switch arr [low] = arr [high]; // The while (low   
3. Sorting scheme for optimizing small arrays

Fast sorting is applicable to solutions for very large arrays. in the opposite case, if the array is very small, in fact, quick sorting is better than direct insertion sorting (direct insertion is the best performance in simple sorting ). The reason is that recursive operations are used for quick sorting. When sorting a large amount of data, this performance impact can be ignored as opposed to its overall algorithm advantage. However, if the array has only a few records to be sorted, this is a small use, so we need to improve the QSort function.

Package QuickSort; public class QuickSortRealize4 {final static int MAX_LENGTH_INSERT_SORT = 7; public static void QuickSort (int [] arr) {QSort (arr, 0, arr. length-1);} // sort the subsequences of the ordered table quickly. The minimum and maximum values of the subsequences to be sorted are low and high public static void QSort (int [] arr, int low, int high) {int lower; if (high-low)> MAX_LENGTH_INSERT_SORT) {lower = Partition (arr, low, high ); // split the array sub-sequence into QSort (arr, low, limit-1); // recursively sorts QSort (arr, Else + 1, high); // recursive sorting of the high sub-Table} else {insertSort (arr) ;}// select a keyword and try your best to place it in one location, so that the value on the left is smaller than it, // The value on the right is bigger than it. We call this keyword pivot. Public static int Partition (int [] arr, int low, int high) {if (arr = null | low <0 | high> = arr. length) {new Exception () ;}int foreign tkey; Foreign tkey = arr [low]; // select the first record as the pivot record int tempCopy = foreign tkey; // back up the pivot value to tempCopy while (low  = Pivotkey) {// if it is greater than the pivot value, the subscript is reduced by one. Otherwise, the loop jumps out. High --;} // Swap (arr, low, high); // switch arr [low] = arr [high]; // The while (low  Arr [I]) {// temp = 2 int temp = arr [I]; // you must ensure that the array subscript is greater than or equal to 0, for Loop for (j = I-1; j> = 0 & arr [j]> temp; j --) {arr [j + 1] = arr [j]; // arr [1] = 4} // j =-1 arr [j + 1] = temp; // arr [0] = 2 // 2 4 1 7 8 }}public static void main (String [] args) {int [] arr = {50, 10, 90, 30, 70, 40, 80, 60, 20}; QuickSort (arr); // insertSort (arr); for (int array: arr) {System. out. print (array + "");} System. out. println ();}}  

We have added a judgment that when high-low is not greater than a constant (some data points out that 7 is more appropriate, 5 is more reasonable, and the actual application can be adjusted as appropriate ), directly Insert the sorting to maximize the advantages of the two sorting methods.

4. Optimize recursive operations

We know that recursion has a certain impact on performance, and the QSort function isThere are two recursive operations at the end.
If the sequence to be sorted is extremely unbalanced, the recursive depth will approach N, rather than the logN in the balance, not just the speed problem, but the stack size is very limited, each recursive call consumes a certain amount of space. The more function parameters, the more space each recursion consumes. If recursion can be reduced, the performance will be improved. Implementation of QSortTail recursion Optimization.

Package QuickSort; public class QuickSortRealize5 {final static int MAX_LENGTH_INSERT_SORT = 7; public static void QuickSort (int [] arr) {QSort (arr, 0, arr. length-1);} // sort the subsequences of the ordered table quickly. The minimum and maximum values of the subsequences to be sorted are low and high public static void QSort (int [] arr, int low, int high) {int lower; if (high-low)> MAX_LENGTH_INSERT_SORT) {while (low  = Arr. length) {new Exception () ;}int foreign tkey; Foreign tkey = arr [low]; // select the first record as the pivot record int tempCopy = foreign tkey; // back up the pivot value to tempCopy while (low  = Pivotkey) {// if it is greater than the pivot value, the subscript is reduced by one. Otherwise, the loop jumps out. High --;} // Swap (arr, low, high); // switch arr [low] = arr [high]; // The while (low  Arr [I]) {// temp = 2 int temp = arr [I]; // you must ensure that the array subscript is greater than or equal to 0, for Loop for (j = I-1; j> = 0 & arr [j]> temp; j --) {arr [j + 1] = arr [j]; // arr [1] = 4} // j =-1 arr [j + 1] = temp; // arr [0] = 2 // 2 4 1 7 8 }}public static void main (String [] args) {int [] arr = {50, 10, 90, 30, 70, 40, 80, 60, 20}; QuickSort (arr); // insertSort (arr); for (int array: arr) {System. out. print (array + "");} System. out. println ();}}   

After we change if to while, because after the first recursion,The variable low is useless, so you can assign Limit + 1 to low,After recycling, a Partition will take place.
(Arr, low, high), the effect is equivalent to "QSort (arr, latency + 1, high );". The results are the same,Instead of recursive methods, stack depth can be reduced.To improve the overall performance.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.