Now let's look back at these algorithms and use the best methods to describe these algorithms based on our own experiences to help you understand their working principles and programming skills. This article is suitable for reading the materials prepared for the java interview.
First, attach a test report:
Array length: 20000
BubbleSort: 766 MS
BubbleSortAdvanced: 662 MS
BubbleSortAdvanced2: 647 MS
SelectSort: 252 MS
InsertSort: 218 MS
InsertSortAdvanced: 127 MS
InsertSortAdvanced2: 191 MS
BinaryTreeSort: 3 MS
ShellSort: 2 MS
ShellSortAdvanced: 2 MS
ShellSortAdvanced2: 1 MS
MergeSort: 3 MS
QuickSort: 1 MS
HeapSort: 2 MS
Through testing, we can think that the Bubble Sorting has reason to be thrown into the waste bin. The only reason for its existence may be better understood. I did not think of the Efficiency of hill sorting; it is difficult to understand and write heap sorting, and there should be a macro thinking.
Copy codeThe Code is as follows: package algorithm. sort;
Import java. lang. reflect. Method;
Import java. util. Arrays;
Import java. util. Date;
/**
* Set of common Java sorting algorithms and performance tests
*
* This set of programs covers the compilation of common sorting algorithms, and explains the working principles of various algorithms in conjunction with extremely simple special cases in annotations for easy understanding and absorption;
* Many Wikipedia and other blog examples are used in programming, and you can use your own ideas to select and improve a method that is most understandable.
* (Especially for fast sorting, I think the algorithm I write is best understood ).
* A centralized performance test and correctness test method are provided to facilitate observation.
* @ Author/link. php? Url = http://blog.csdn.net/sunxing007
* For reprint, please indicate from/link. php? Url = http://blog.csdn.net/sunxing007
*/
Public class SortUtil {
// A set of tested methods
Static String [] methodNames = new String [] {
"BubbleSort ",
"BubbleSortAdvanced ",
"BubbleSortAdvanced2 ",
"SelectSort ",
"InsertSort ",
"InsertSortAdvanced ",
"InsertSortAdvanced2 ",
"BinaryTreeSort ",
"ShellSort ",
"ShellSortAdvanced ",
"ShellSortAdvanced2 ",
"MergeSort ",
"QuickSort ",
"HeapSort"
};
Public static void main (String [] args) throws Exception {
// CorrectnessTest ();
PerformanceTest (20000 );
}
/**
* Correctness test <br>
* Test the correctness of each algorithm. <br>
* It is only for the convenience of observing whether the newly added algorithm is basically correct. <br>
* @ Throws Exception mainly refers to reflection-related exceptions. <br>
*/
Public static void correctnessTest () throws Exception {
Int len = 10;
Int [] a = new int [len];
For (int I = 0; I <methodNames. length; I ++ ){
For (int j = 0; j <a. length; j ++ ){
A [j] = (int) Math. floor (Math. random () * len * 2 );
}
Method sortMethod = null;
SortMethod = SortUtil. class. getDeclaredMethod (methodNames [I], a. getClass ());
Object o = sortMethod. invoke (null, );
System. out. print (methodNames [I] + ":");
If (o = null ){
System. out. println (Arrays. toString ());
}
Else {
// Take into account mergeSort, and its sorting result appears in the form of a return value;
System. out. println (Arrays. toString (int []) o ));
}
}
}
/**
* Performance test <br>
* Input the array length using the len parameter. Each method runs for 20 times and obtains the average time consumption. <br>
* @ Param len the length of the array is recommended to be greater than 10000. Otherwise, some algorithms will show that the time consumed is 0. <br>
* @ Throws Exception mainly refers to reflection-related exceptions. <br>
*/
Public static void performanceTest (int len) throws Exception {
Int [] a = new int [len];
Int times = 20;
System. out. println ("Array length:" + a. length );
For (int I = 0; I <methodNames. length; I ++ ){
Method sortMethod = null;
SortMethod = SortUtil. class. getDeclaredMethod (methodNames [I], a. getClass ());
Int totalTime = 0;
For (int j = 0; j <times; j ++ ){
For (int k = 0; k <len; k ++ ){
A [k] = (int) Math. floor (Math. random () * 20000 );
}
Long start = new Date (). getTime ();
SortMethod. invoke (null, );
Long end = new Date (). getTime ();
TotalTime + = (end-start );
}
System. out. println (methodNames [I] + ":" + (totalTime/times) + "ms ");
// System. out. println (Arrays. toString ());
}
}
/**
* The most primitive sort of bubble swapping; <br>
* Two-layer traversal: the outer layer controls the number of scans and the inner layer controls the number of comparisons. <br>
* Each time the outer layer is scanned, there is a largest element under the background. Therefore, the number of comparisons within the outer layer will gradually decrease. <br>
*/
Public static void bubbleSort (int [] ){
For (int I = 0; I <a. length; I ++ ){
For (int j = 0; j <a. length-i-1; j ++ ){
If (a [j]> a [j + 1]) {
Int tmp = a [j];
A [j] = a [j + 1];
A [j + 1] = tmp;
}
}
}
}
/**
* Improved Bubble Method <br>
* Improvement: A flag is set. If no exchange occurs during a trip, it indicates that it has been arranged. <br>
*/
Public static void bubbleSortAdvanced (int [] ){
Int k = a. length-1;
Boolean flag = true;
While (flag ){
Flag = false;
For (int I = 0; I <k; I ++ ){
If (a [I]> a [I + 1]) {
Int tmp = a [I];
A [I] = a [I + 1];
A [I + 1] = tmp;
// If there is an exchange, the flag is maintained;
Flag = true;
}
}
K --;
}
}
/**
* Improved Bubble Method 2 <br>
* The improvement lies in absorbing the above ideas (there is no exchange which means they are already ordered). If the local ones are already ordered, the subsequent comparisons do not need to be compared. <Br>
* For example: 3142 5678. If the exchange between 2 and 4 has just been completed and it is found that there is no exchange after the comparison, then the subsequent comparison only needs to be compared to 4. <br>
* This algorithm uses a flag to record the last occurrence and comparison location of a trip. <br>
*/
Public static void bubbleSortAdvanced2 (int [] ){
Int flag = a. length-1;
Int k;
While (flag> 0 ){
K = flag;
Flag = 0;
For (int I = 0; I <k; I ++ ){
If (a [I]> a [I + 1]) {
Int tmp = a [I];
A [I] = a [I + 1];
A [I + 1] = tmp;
// If there is an exchange, the last comparative location of the trip will be recorded;
Flag = I + 1;
}
}
}
}
/**
* Insert sorting
*
* There are several conventions on insert sorting to quickly understand the algorithm: <br>
* I: unordered table traversal subscript; I <n-1; <br>
* J: traverse the following table in an ordered table; 0 <= j <I; <br>
* A [I]: unordered header elements that are currently taken out for insertion sorting. <br>
* A [j]: Any element in an ordered table. <br>
* <Br>
* Algorithm key point: divide the array into a [0 ~ I-1] ordered table, a [I ~ N-1] unordered table. One table is retrieved from the unordered table header each time. <br>
* Insert it to the proper position of the ordered table until the unordered table is empty. <br>
* Initially, a [0] is an ordered table, and a [1 ~ N-1] is an unordered table. <br>
*/
Public static void insertSort (int [] ){
// Traverse the unordered table header;
For (int I = 1; I <a. length; I ++ ){
Int j;
// Compare the elements of a [I] And the ordered table to find an appropriate position;
For (j = I-1; j> = 0; j --){
If (a [j] <a [I]) {
Break;
}
}
// If an appropriate position is found, the elements are moved toward the rear of the grid starting from this position to free up space for the inserted elements;
If (j! = (I-1 )){
Int tmp = a [I];
Int k;
For (k = I-1; k> j; k --){
A [k + 1] = a [k];
}
A [k + 1] = tmp;
}
}
}
/**
* Improved insert sorting 1
* The Key To improvement is: first, compare the unordered Header element a [I] With the order table end a [I-1,
* If a [I] <a [I-1], the adjustment is required. The adjustment process is:
* Starting from the end of an ordered table, all the elements in the ordered table larger than a [I] Move toward the back until an appropriate position is found;
*/
Public static void insertSortAdvanced (int [] ){
// Traverse unordered tables;
For (int I = 1; I <a. length; I ++ ){
// If the unordered Header element is smaller than the end of the ordered table, it must be adjusted;
If (a [I] <a [I-1]) {
Int tmp = a [I];
Int j;
// Search and compare the beginning and end of an ordered table, and move the elements greater than a [I] to the back to free up space;
For (j = I-1; j> = 0 & a [j]> tmp; j --){
A [j + 1] = a [j];
}
A [j + 1] = tmp;
}
}
}
/**
* Improved insert sorting 2
* The general idea is similar to the above. The unordered table Header element is used to compare the elements from the end of the ordered table to the front,
* If a [I] is smaller than a [I-1], move a [I] forward from the end of the ordered table in a bubble exchange until it reaches the proper position;
*/
Public static void insertSortAdvanced2 (int [] ){
// Traverse unordered tables
For (int I = 1; I <a. length; I ++ ){
// Bubble from the end of the ordered table with a [I;
For (int j = I-1; j> = 0 & a [j]> a [j + 1]; j --) {// a [j + 1] is a [I]
Int tmp = a [j];
A [j] = a [j + 1];
A [j + 1] = tmp;
}
}
}
/**
* Fast sorting <br>
* The idea of an algorithm is to divide and conquer it: first find an element (generally an array Header element), put all elements larger than it to the right, and put all elements smaller than it to the left; <br>
* Then, follow these steps to process two sub-arrays. The sub-array Header element refers to the elements used to divide the array. <br>
* <Br>
* The following key points of the program are! Forward, low0 ++, and high0 -- these operations make a [low0] And a [high0] always have an element pointing to the Child array header. <br>
* The operation of these three values can be easily understood in extreme situations: <br>
* If my series is 0123456789, forward = false at the beginning, and 0 are used as the basis for subarray division, it is clear that no exchange will occur in the first round, and low0 always points to 0, <br>
* High0 gradually drops until it points to 0. Similarly, you can consider the 9876543210 example. <br>
* <Br>
* @ Param a: array to be sorted <br>
* @ Param low subarray start subscript; <br>
* @ Param high subarray subscript; <br>
*/
Public static void quickSort (int [] a, int low, int high ){
If (low> = high ){
Return;
}
Int low0 = low;
Int high0 = high;
Boolean forward = false;
While (low0! = High0 ){
If (a [low0]> a [high0]) {
Int tmp = a [low0];
A [low0] = a [high0];
A [high0] = tmp;
Forward =! Forward;
}
If (forward ){
Low0 ++;
}
Else {
High0 --;
}
}
Low0 --;
High0 ++;
QuickSort (a, low, low0 );
QuickSort (a, high0, high );
}
/**
* Simple calling method for quick sorting <br>
* Convenient test and call <br>
* @ Param
*/
Public static void quickSort (int [] ){
QuickSort (a, 0, a. length-1 );
}
/**
* Merge and sort <br>
* Merging means merging two ordered arrays. Merging and sorting also uses the divide-and-conquer idea to divide an array into several sub-arrays. <br>
* When the length of the sub-array is 1, the sub-array is ordered and can be merged in two or two ways. <br>
* <Br>
* Because Merge Sorting requires a space to be allocated to dump the merge results, the results of the merge algorithm are returned in the form of a return value for the convenience of the algorithm. <br>
*/
/**
* Merge two ordered arrays
* @ Param a ordered array 1
* @ Param B ordered array 2
* @ Return: sorted array after merging;
*/
Public static int [] merge (int [] a, int [] B ){
Int result [] = new int [a. length + B. length];
Int I = 0, j = 0, k = 0;
While (I <a. length & j <B. length ){
If (a [I] <B [j]) {
Result [k ++] = a [I];
I ++;
}
Else {
Result [k ++] = B [j];
J ++;
}
}
While (I <a. length ){
Result [k ++] = a [I ++];
}
While (j <B. length ){
Result [k ++] = B [j ++];
}
Return result;
}
/**
* Merge and sort <br>
* Splits the array into two parts from the middle and recursively calls the left and right parts until the array length is 1, and then merges the two parts. <br>
* @ Param: array to be sorted;
* @ Return ordered array;
*/
Public static int [] mergeSort (int [] ){
If (a. length = 1 ){
Return;
}
Int mid = a. length/2;
Int [] leftPart = new int [mid];
Int [] rightPart = new int [a. length-mid];
System. arraycopy (a, 0, leftPart, 0, leftPart. length );
System. arraycopy (a, mid, rightPart, 0, rightPart. length );
LeftPart = mergeSort (leftPart );
RightPart = mergeSort (rightPart );
Return merge (leftPart, rightPart );
}
/**
* Select sorting <br>
* Similar to insertion sorting, an array is also divided into ordered and unordered partitions. The difference is: <br>
* Insert and sort are used to insert the first element of the unordered area to an appropriate position in the ordered area. <br>
* Sorting is to select the smallest value from the unordered area and put it at the end of the ordered area. <br>
* <Br>
* Two-layer loops control the tail of an ordered area, and the inner layer is used to find the smallest element in the disordered area. <br>
* @ Param
*/
Public static void selectSort (int [] ){
For (int I = 0; I <a. length; I ++ ){
Int minIndex = I;
For (int j = I + 1; j <a. length; j ++ ){
If (a [j] <a [minIndex]) {
MinIndex = j;
}
}
Int tmp = a [I];
A [I] = a [minIndex];
A [minIndex] = tmp;
}
}
/**
* Hill sorting <br>
* The idea is to divide an array into multiple sub-Sequences Based on the same step size (/spacing), and sort each sub-sequence by normal insertion. <br> step size is reduced gradually, when the value is 1, The last normal insertion sorting is performed;
* Using an extreme example as an example, I have the following series: <br>
* [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; <br>
* In the initial phase, the step size gap is 5. Then, the sub-array is divided into [], [], [], [], []; <br> sort them separately (of course, The results remain unchanged because of the special array). <br>
* Then gap = 2 = 5/2; the sub-array is [, 9], [, 10]; <br>
* Last gap = 1 = 2/2; perform a global sorting. <br>
* <Br>
* Hill sorting overcomes the weakness of insert/Bubble Sorting (only one adjacent position can be moved at a time). <br> relying on the large step size, you can move the element to the target location (or nearby) as soon as possible. <br>
* Hill sorting is actually a variant of insert sorting. It applies to: When the array is in an overall order and needs to be adjusted individually, the efficiency of O (n) can be achieved by taking advantage of insert sorting. <br>
* An important factor affecting the hill algorithm is step size selection. The advantage of a good step size is that the subsequent short step sorting does not damage the previous long step sorting. <br>
* How can this damage be understood? The previous long step moves a small number to the left, however, after narrowing down the step size, it may be switched to the right (because it is divided into many smaller groups); <br>
* About the step size, you can view the http://zh.wikipedia.org above the page about the hill sorting; <br>
* The following program is the most basic method of hill sorting, which is suitable for understanding Hill sorting ideas. <br>
*/
Public static void shellSort (int [] ){
// Control the spacing. The spacing gradually decreases until it is 1;
For (int gap = a. length/2; gap> 0; gap/= 2 ){
// Scan each sub-array
For (int I = 0; I <gap; I ++ ){
// Scan the unordered area for each word group. Pay attention to the increment;
// A [I] is the initial ordered area;
For (int j = I + gap; j <a. length; j + = gap ){
// The first element of the unordered area is smaller than the last element of the ordered area, indicating that the element needs to be adjusted.
If (a [j] <a [j-gap]) {
Int tmp = a [j];
Int k = j-gap;
// Search for the appropriate position from the end of the ordered area;
While (k> = 0 & a [k]> tmp ){
A [k + gap] = a [k];
K-= gap;
}
A [k + gap] = tmp;
}
}
}
}
}
/**
* Improved Hill sorting <br>
* Improvement: the above statement treats each word group differently using a for loop, which is actually unnecessary. <br>
* A [,... gap-1] is the ordered area of all sub-arrays. a [gap,... n-1] is the disordered area of all word groups. <br>
* <Br>
* This improvement does not improve the time efficiency, but makes the program look more concise. <br>
* @ Param
*/
Public static void shellSortAdvanced (int [] ){
// Control the step size
For (int gap = a. length/2; gap> 0; gap/= 2 ){
// Start processing from the unordered area and put multiple sub-arrays together for processing;
For (int j = gap; j <a. length; j ++ ){
// The following logic is the same as above;
If (a [j] <a [j-gap]) {
Int tmp = a [j];
Int k = j-gap;
While (k> = 0 & a [k]> tmp ){
A [k + gap] = a [k];
K-= gap;
}
A [k + gap] = tmp;
}
}
}
}
/**
* Improved Hill sorting 2 <br>
* Based on the shellSortAdvanced idea, insertAdvanced2 is adopted. <br> that is, the first element of the unordered area is moved to the appropriate position in the bubble form. <br>
* @ Param
*/
Public static void shellSortAdvanced2 (int [] ){
For (int gap = a. length/2; gap> 0; gap/= 2 ){
For (int I = gap; I <a. length; I ++ ){
If (a [I] <a [I-gap]) {
For (int j = I-gap; j> = 0 & a [j + gap]> a [j]; j-= gap ){
Int tmp = a [j];
A [j] = a [j + gap];
A [j + gap] = tmp;
}
}
}
}
}
/**
* Heap sorting <br>
* Definition of heap: the heap is a completely or almost complete binary tree. The value of the heap top element is greater than that of the left and right children. The left and right children must also meet this condition. <br>
* According to the definition of the heap, the heap can be a maxHeap or minHeap. <br>
* The binary tree can be simulated with arrays. For any element I, the left child is 2 * I + 1, The right child is 2 * I + 2; the parent node is (I-1)/2;
* @ Param
*/
Public static void heapSort (int [] ){
// First adjust from the last non-leaf node to satisfy the heap structure;
For (int I = (a. length-2)/2; I> = 0; I --){
MaxHeapAdjust (a, I, a. length );
}
// Exchange the last node with the first node, and adjust the heap until the heap is reached;
For (int I = a. length-1; I> 0; I --){
Int tmp = a [I]; a [I] = a [0]; a [0] = tmp;
MaxHeapAdjust (a, 0, I );
}
}
/**
* Adjust the heap <br>
* Change the binary tree with I as the heel node to a heap. <br>
* You can think about this process like this: This Complete Binary Tree is like a pyramid. The small elements on the top of the tower are settled down along the tree structure. <br>
* The result of the adjustment is that the largest element is at the top of the pyramid and is deleted from the heap (swap it to the end of the heap, and then collapse the heap to a grid). <br>
* The reason for fast heap sorting is that according to the characteristics of a binary tree, a node must be settled to a proper position, and only logn steps are required. At the same time, the adjusted Results (size order) in the early stage will be recorded, this accelerates subsequent adjustments. <br>
* @ Param a: array to be sorted
* @ Param I heap top
* @ Param len heap Length
*/
Public static void maxHeapAdjust (int [] a, int I, int len ){
Int tmp = a [I];
// J is the left child node
Int j = I * 2 + 1;
//
While (j <len ){
// Select large ones from left and right children
// J + 1 is the right child node
If (j + 1) <len & a [j + 1]> a [j]) {
J ++;
}
// No longer find the proper location
If (a [j] <tmp ){
Break;
}
// Otherwise, move the larger person up the tree;
A [I] = a [j];
// I points to the older child;
I = j;
// J points to the new left child node;
J = 2 * I + 1;
}
// Sink the node value to a proper position;
A [I] = tmp;
}
/**
* Binary Tree sorting <br>
* The binary tree is defined as nested: <br> the value of a node is greater than that of a left leaf node and smaller than that of a right leaf node. The leaf node also meets this requirement. <br>
* The binary tree construction process is the sorting process: <br>
* Construct the heel node first, and then call the add method to add the child nodes of the heel node. This process is also nested. <br>
* <Br>
* An ordered result is obtained by traversing a binary tree in a central order. <br>
* Binary Tree sorting is used in special cases. The usage depends on the situation. <br>
* @ Param
*/
Public static void binaryTreeSort (int [] ){
// Construct an internal class of a binary tree node to implement the binary tree sorting algorithm;
Class BinaryNode {
Int value;
BinaryNode left;
BinaryNode right;
Public BinaryNode (int value ){
This. value = value;
This. left = null;
This. right = null;
}
Public void add (int value ){
If (value> this. value ){
If (this. right! = Null ){
This. right. add (value );
}
Else {
This. right = new BinaryNode (value );
}
}
Else {
If (this. left! = Null ){
This. left. add (value );
}
Else {
This. left = new BinaryNode (value );
}
}
}
/**
* Traversing a binary tree in the middle order is ordered.
*/
Public void iterate (){
If (this. left! = Null ){
This. left. iterate ();
}
// Disable the output during the test to avoid affecting the performance;
// System. out. print (value + ",");
If (this. right! = Null ){
This. right. iterate ();
}
}
}
BinaryNode root = new BinaryNode (a [0]);
For (int I = 1; I <a. length; I ++ ){
Root. add (a [I]);
}
Root. iterate ();
}
}