Java Sorting Algorithm quick sorting

Source: Internet
Author: User

Sorting is a type of operation that is often performed in a computer. Its purpose is to adjust a set of "unordered" record sequences to "ordered" record sequences. Next let's take a look at quick sorting.

AD:

Quicksort is an improvement in Bubble sorting. Its basic idea is: Split the data to be sorted into two independent parts by one sort, and all the data in one part is smaller than all the data in the other part, then, sort the two data parts by using this method. The entire sorting process can be recursive to convert the entire data into an ordered sequence. Fast sorting is unstable. The extra space of O (log (n) is not adaptive because the time complexity is O (nlog (n.

Quick Sort has several variant algorithms worth mentioning. Here is a brief introduction:

Randomization fast sorting: the worst case of fast sorting is based on the choice of the principal component for each division. Select the first element as the principal element for basic quick sorting. In this way, when the array is ordered, the worst result is obtained for each division. A common optimization method is the randomization algorithm, that is, randomly selects an element as the principal component. In this case, although the worst case is O (n ^ 2), the worst case is no longer dependent on input data, but the random function value is not good. In fact, the probability of a rapid randomization sorting to obtain the theoretical worst case is only 1/(2 ^ n ). Therefore, the random fast sorting can be performed on the time complexity of the vast majority of input data reaching O (nlogn. A predecessor made an incisive conclusion: "randomization and fast sorting can satisfy a person's character needs for a lifetime ."

The only drawback of rapid randomization sorting is that, once many identical data are input, the Randomization effect will be reduced directly. For the limit condition, that is, for n identical number sorting, the time complexity of the Randomization fast sorting will undoubtedly be reduced to O (n ^ 2 ). The solution is to use a method for scanning so that the principal component is retained in the original position without switching.

BalancedQuicksort: whenever possible, select an element that can represent the median as the key data, and then compare, replace, and recursively follow the principle of regular quickrank. Generally, the method for selecting this data is to take the start, end, and center data and select the value through comparison. The advantage of taking these three values is that in actual problems (such as the competition in informatics ......) Medium, there is a high probability of an approximate sequence data or a reverse sequence data. At this time, the intermediate data must be the mean value, which is also the actual approximate mean value. In case of data that happens to be big on both sides (or vice versa) in the middle, the retrieved values are close to the nearest value, because at least two parts can be separated, the actual efficiency will increase by about two times, it is also conducive to slightly disrupting data and damaging the degraded structure.

ExternalQuicksort: the key data is a buffer, first, read the previous and subsequent M/2 elements into the buffer and sort these elements in the buffer, and then read the next element from the beginning (or end) of the sorted array, if this element is smaller than the smallest element in the buffer, it is written to the space at the beginning; if this element is greater than the largest element in the buffer, it is written to the final space; otherwise, the maximum or minimum element in the buffer is written into the array and the element is put in the buffer. Keep the maximum value lower than the key data, and the minimum value is higher than the key data, so as to avoid re-arrangement of the intermediate data. After completion, the middle space of the array must be empty, and the buffer is written into the middle space of the array. Then recursively sorts the smaller external parts cyclically.

Three-way Radix Quicksort (also called MultikeyQuicksort and Multi-key Quicksort) it is a more efficient algorithm in string sorting. This algorithm is used to sort the elements of an array, that is, multikey, such as a string. Each letter can be considered as a key. The algorithm selects an element as the key data in the sorted array at any time. First, only the first key (letter) of the element is considered ), then, the comparison of other elements by key is divided into three parts: less than, equal to, and greater than key data. Then, recursively sort the "less than" and "greater than" parts based on this key location, and sort the "equal to" parts based on the next key.

Quick sorting is the most widely used sorting algorithm. The core of quick sorting is the segmentation algorithm, which can be said to be the most skillful part. I hope this article will help you.

Code 1:

 

[Java]
Public static voidquickSort (int [] a, int low, int high ){
 
Int n = a. length;
 
Int I = low;
 
Int j = high;
 
Int temp = a [low];
 
While (I <j ){
 

 
// The scan must start from the right. Otherwise, when an element is larger than it is scanned from the left side (isn't there a blank space on the left side? But it is definitely not suitable to put it on the left.) Put it on the right, where should it be, And put it anywhere will overwrite a data so it is not used. This is a serious error.
 
While (I <j & a [j]> = temp ){
 
J --; // release
 
}
 
If (I <j ){
 
A [I] = a [j];
 
I ++; // Let go and start the left-side Loop
 
}
 
While (I <j & a [I] <temp) {// note: "<" rather than <= this detail indicates that even if it is equal to temp, it should be placed behind it to ensure that-the principle of maintaining the original order while the values are consistent!
 
I ++;
 
}
 
If (I <j ){
 
A [j] = a [I];
 
J --;
 
}
 
}
 
A [I] = temp;
 
// It is possible that I = low, for example, a [low] is the smallest, at the beginning, the loop is always j -- it is always reduced to I = j and then assigned a value (that is, it should be in the first place). It is also possible that a [low] is the largest, always from I ++ to high. If so, you do not need to sort the subinterval, so the if statement is used below.
 
If (I> low) quickSort (a, low, I-1 );
 
If (I  

 
}
 
Public static voidmain (String [] args ){
 

 
Int [] a = {, 27 };
 
QuickSort (a, 0, a. length-1 );
 
Print ();
 
}
 
// Add a print () method to print the array ()
 
Public static voidprint (int [] ){
 
Int n = a. length;
 
For (inti = 0; I <n; I ++ ){
 
System. out. print (a [I] + "");
 
If (I + 1) % 5 = 0 ){
 
System. out. println ();
 
}
 
}
 
System. out. println ();
 
}
 
}

 

Code 2:


[Java]
Public class quickSort2 {

Public static void main (String [] args ){
// Declare an array
Int [] nums = {, 27,-77 };
// Application quick sorting method
QuickSort (nums, 0, nums. length-1 );
// Display the sorted Array
For (int I = 0; I <nums. length; ++ I ){
System. out. print (nums [I] + ",");
}
System. out. println ("");
}

Public static void quickSort (int [] a, int M, int K ){
Int lo = M;
System. out. println ("lo is left to right and the initial value is:" + lo );
Int hi = K;
System. out. println ("hi is from right to left, initial value:" + hi );
If (lo> = hi ){
System. out. print ("lo:" + lo + "hi:" + hi );
System. out. println ("because lo:" + lo + "> = hi:" + hi + "is returned !! ");
Return;
}
// Determine the logic variable of the pointer direction
Booleantransfer = true;
While (lo! = Hi ){
System. out. println ("lo value:" + lo );
System. out. println ("hi value:" + hi );


If (a [lo]> a [hi]) {
// Exchange numbers
Int temp = a [lo];
A [lo] = a [hi];
A [hi] = temp;
System. out. println ("exchanged digits! "+ A [lo] +" and "+ a [hi] +" are exchanged. The temp value is: "+ temp );

// Display the changes of the array numbers for each comparison
System. out. print ("the order of the current array is :");
For (int I = 0; I <a. length; ++ I ){
System. out. print (a [I] + ",");
}
System. out. println ("special mark M:" + M );
// Determines whether to move or not. This switch is a pendulum, and it takes turns to be true or false! The trigger condition is exchange!
Transfer = (transfer = true )? False: true;
System. out. println ("the pointer is about to move! The value of transfer is: "+ transfer );
}


// Move the pointer forward or backward. By default, lo ++ is used. Note that! Switching may not necessarily change transfer to true! --,
If (transfer ){
Hi --;
System. out. println ("hi is reduced by 1 ");
}
Else {
Lo ++;
System. out. println ("lo is added with 1 ");
}
}
System. out. println ("while loop exits, lo and hi are equal to:" + lo + "=" + hi );
// Separate the array by two halves to determine the correct position of each number. This operation is performed separately during return.

Lo --;
Hi ++;
System. out. println ("separates the array into two halves to determine the correct position of each number. Now the values of lo and hi are:" + lo + "" + hi );
System. out. println ("M value:" + M );
// The Magic M. Because no value can be passed, M has always been the "0" passed by the original program"
System. out. println ("quickSort (a, M, lo )");
System. out. println ("M:" + M + "K:" + K + "hi:" + hi + "lo:" + lo );
QuickSort (a, M, lo );
System. out. println ("after calling the program M:" + M + "K:" + K + "hi:" + hi + "lo:" + lo );


System. out. println ("quickSort (a, hi, K );");
QuickSort (a, hi, K );
System. out. println ("after calling the program M:" + M + "K:" + K + "hi:" + hi + "lo:" + lo );
}
}


Author: hjm4702192

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.