6 kinds of sorting algorithms used in Java in detail decomposition _java

Source: Internet
Author: User

Sorting algorithms are used in many places, and recently looked again at the algorithm, and their simple implementation of the once again, hereby record down, for later review leave some material.

Needless to say, let's look at the classic sorting algorithm:

1. Select sort

The basic idea of choosing a sort is to iterate through the array, with I representing the ordinal of the current order, you need to find the minimum value in the remaining [i...n-1], and then swap the smallest value you find with the value I point to. Because each trip to determine the elements of the process will have a selection of the maximum value of the sub-process, so people are called the choice of sorting. For example, take a look at:

Initial: [38, 17, 16, 16, 7, 31, 39, 32, 2, 11]





i = 0: [2, A, 7,, April, one] (0th [38]<->8th [2])





i = 1: [2, 7, A,, one] (1st [38]<->4th [17])





i = 2: [2, 7, one,, MB] (2nd [11]<->9th [16])





i = 3: [2, 7, 11, 16, 17, 31, 39, 32, 38, 16] (without switching)





i = 4: [2, 7, one,, MB] (4th [17]<->9th [16])





i = 5: [2, 7, one,,, Q] (5th [31]<->9th [17])





i = 6: [2, 7, one,, and,] (6th [39]<->9th [31])





i = 7: [2, 7, 11, 16, 16, 17, 31, 32, 38, 39] (without switching)





i = 8: [2, 7, 11, 16, 16, 17, 31, 32, 38, 39] (without switching)





i = 9: [2, 7, 11, 16, 16, 17, 31, 32, 38, 39] (without switching)

As can be seen from the example, the selection sort will grow with the order (I gradually increase), comparisons are less frequent, but regardless of whether the array is initially ordered, the selection is compared from I to the end of the array, so the number of comparisons for the given length of the array is fixed: 1 + 2 + 3 + ... + n = n * (n + 1)/2, while the number of exchanges is related to the order of the initial array, if the initial array order is random, then in the worst case, the array elements will be exchanged n times, and the best case may be 0 times (the array itself is ordered).

As a result, the time complexity and space complexity of the selection order are O (N2) and O (1), respectively (selection of the sorting requires only one extra space for array element Exchange).

Implementation code:

Copy Code code as follows:



/**


* Selection Sorting


*/


SELECTION (new sortable () {


Public <t extends comparable<t>> void sort (t[) array, Boolean ascend) {


int len = Array.Length;


for (int i = 0; i < len; i++) {


int selected = i;


for (int j = i + 1; J. < Len; j + +) {


int compare = Array[j].compareto (array[selected]);


if (compare!= 0 && Compare < 0 = = Ascend) {


selected = j;


}


}





Exchange (array, I, selected);


}


}


})


2. Insert Sort

The basic idea of the insertion sort is that, in the process of traversing an array, the elements before ordinal I, that is, [0..i-1] are already sorted, this trip needs to find the correct position K of the element x of I, and in the process of finding this position K, move the comparison element back one at a point, the element x "Teng position", and finally Assigns k to an element value of x, and the insertion sort is also named according to the attributes of the sort.

The following is an instance of a red-flagged number for the inserted number, the missing number is the element that is not involved in this sort, and the element between the red mark and the missing digit is a backward-moving element, such as the second participating element is [11, 31, 12], the element to be inserted is 12, but 12 The current is not in the right position, so we need to be compared to the previous elements 31, 11, while comparing the elements to move the comparison, until we find the first element 12 smaller than 11 o'clock stop the comparison, at this point 31 of the corresponding index 1 is 12 need to insert the location.

Initial:    [5, 12, 5, 34, 30, 26, 18] 
 
First trip: [11, 31, +] 38, 36, 18] (no moving elements)  
 
Second trip: [11, 12, 31, 5, 34, 30, 26, 38, 36, 18] (31 move backwards)  
 
third trip: [5, 11, 12, 31, 34, 30, 26, 38, 36, 18] (11, 12, 31, move backwards)  
 
Fourth: [5, 11, 12, 31, 34, 30, 2 6, 38, 36, 18] (no moving elements)  
 
Fifth trip: [5, 11, 12, 30, 31, 34, 26, 38, 36, 18] (31, 34, move backwards)  
&NB Sp
Sixth Trip: [5, 11, 12, 26, 30, 31, 34, 38, 36, 18] (30, 31, 34 move backwards)  
 
Seventh trip: [5, 11, 12, 26, 30, 31, 34, 38, 36, 18] (no moving elements)  
 
Eighth trip: [5, 11, 12, 26, 30, 31, 34, 36, 38, 18] (38 move backwards)  
&NBSP ;
Nineth Trip: [5, 11, 12, 18, 26, 30, 31, 34, 36, 38] (26, 30, 31, 34, 36, 38 move backwards)

The insertion sort is better than the selection sort, because it is able to use an advantage of the first part of the array to be sorted in order to effectively reduce the number of comparisons, although the advantage depends on the initial order of the array, In the worst case (the given array is exactly in reverse order) the number of times the insertion order needs to be compared and moved will be equal to 1 + 2 + 3 ... + n = n * (n + 1)/2, in extreme cases, the efficiency of the insertion sort is even worse than the selection order. So the insertion order is an unstable sort method, and the insertion efficiency is closely related to the initial order of the array. In general, the time complexity and space complexity of the insertion sort are O (N2) and O (1) respectively.

Implementation code:

Copy Code code as follows:



/**


* Insertion Sorting


*/


Insertion (new sortable () {


Public <t extends comparable<t>> void sort (t[) array, Boolean ascend) {


int len = Array.Length;


for (int i = 1; i < Len; i++) {


T Toinsert = Array[i];


int j = i;


for (; j > 0; j–) {


int compare = Array[j-1].compareto (Toinsert);


if (compare = 0 | | Compare < 0 = ascend) {


Break


}


ARRAY[J] = array[j-1];


}





ARRAY[J] = Toinsert;


}


}


})


3. Bubble sort

Bubble sort can be considered the most classical sort algorithm, remember that the first time the younger brother school contact is the algorithm, because the implementation of the simplest method, two for the loop, the inner loop to determine whether the adjacent two elements in reverse order, is the case of two elements exchange, the outer loop once, can be the remaining elements in the array of the smallest elements "Float" to the front, so call it bubble sort.

As usual, let's take a simple example:

Initial state:   [24, 19, 26, 39, 36, 7, 31, 29, 7, K, G, 23] 
 
, first in (9th [23]<->8th]  
 
Inner layer Second: [7, K, K, A] (8th [23]) (PDF) <->7th [])  
 
Inner layer third trip: [7, Num, K, K] (7th [23]<->6th [31]) & nbsp
 
Inner layer Fourth: [24, 19, 26, 39, 36, 7, 23, 31, 29, 38] (7, 23 are all in the correct order, no need to exchange)  
 
Inner layer Fifth: [24, 7, 5th [7]<->4th [+]]  
 
Inner Sixth trip: [24, 19, 26, 7, 39, 36,, G]. 7 (4th [7]<->3rd])  
 
Inner layer seventh trip: [A] (3r.) (+) (+) (+)-- d [7]<->2nd [])  
 
Inner eighth trip: [7, Num, K, c] (2nd [7]<->1st] [19 ]  
 
Inner layer nineth: [7, 7]<->0th, K, K] (1st [a]  
  ")"
.....

In fact, bubble sort is more like the choice sort, the number of comparisons is the same as n * (n + 1)/2, but the bubble sort takes an extra swap in the process of picking the minimum value (the bubble sort is exchanged when the order of the adjacent elements is found in the sort, which corresponds to the selection sort, It is only after the inner loop comparison ends that the exchange is decided according to the situation, so it seems to me that the selection sort belongs to the improved version of the bubbling sort.

Implementation code:

Copy Code code as follows:



/**


* Bubble sorting, it ' s very similar with insertion sorting


*/


BUBBLE (new sortable () {


Public &lt;t extends comparable&lt;t&gt;&gt; void sort (t[) array, Boolean ascend) {


int length = Array.Length;


int lastexchangedidx = 0;


for (int i = 0; i &lt; length; i++) {


Mark the flag to identity whether exchange happened to false


Boolean isexchanged = false;


Last compare and exchange happened before reaching index I


int currorderedidx = LASTEXCHANGEDIDX &gt; I? LASTEXCHANGEDIDX:I;


for (int j = length–1 J &gt; currorderedidx; j–) {


int compare = Array[j-1].compareto (Array[j]);


if (compare!= 0 &amp;&amp; Compare &gt; 0 = = Ascend) {


Exchange (Array, j–1, j);


Isexchanged = true;


Lastexchangedidx = j;


}


}


If no exchange happen means array is already into order


if (isexchanged = = False) {


Break


}


}


}


})

4. Hill sort

The birth of Hill sort is due to the fact that the insertion sort encounters the problem of moving too many elements when dealing with large arrays. The idea of hill sort is to divide a large array into small arrays, divide by gap, such as arrays [1, 2, 3, 4, 5, 6, 7, 8], if separated by gap = Two, can be divided into [1, 3, 5, 7] and [2, 4, 6, 8] Two arrays (corresponding, such as Gap = 3, the divided array is: [1, 4, 7], [2, 5, 8], [3, 6]) then insert the sorted array, wait until each sub array is sorted and then reduce the gap value before repeated steps until Gap = 1 , that is, to insert the entire array, the array has been basically quickly sorted, so the elements that need to move will be very small and small, to solve the insertion of the sort in the processing of large arrays more mobile number of times.

For specific examples, refer to the insert sort.

Hill sorting is an improved version of the insertion sort, which is helpful when the data is large, and it is recommended that you use the insertion sort directly when you have a small amount of data.

Implementation code:

Copy Code code as follows:



/**


* Shell Sorting


*/


SHELL (new sortable () {


Public &lt;t extends comparable&lt;t&gt;&gt; void sort (t[) array, Boolean ascend) {


int length = Array.Length;


int gap = 1;





Use the most next to LENGTH/3 as the


while (Gap &lt; LENGTH/3) {


Gap = Gap * 3 + 1;


}





while (Gap &gt;= 1) {


for (int i = gap; i &lt; length; i++) {


T next = Array[i];


int j = i;


while (J &gt;= Gap) {


int compare = Array[j-gap].compareto (next);


Already find its position


if (compare = 0 | | Compare &lt; 0 = ascend) {


Break


}





ARRAY[J] = Array[j-gap];


J-= Gap;


}


if (j!= i) {


ARRAY[J] = next;


}


}


Gap/= 3;


}





}


})

5. Merge sort

The merge sort uses the recursive return implementation, belong to "divide and conquer", the target array is divided in the middle, after the two arrays are sorted, after sorting, the sequence of two arrays "merged" together, the most important merge sort is the "merge" process, The merging process requires additional space to be consistent with the two number of group leaders that need to be merged. For example, the arrays to be specified are: [3, 6, 8, 11] and [1, 3, 12, 15] (although logically divided into two arrays, but in fact these elements are still in the original array, just through some index will It is divided into two arrays, the original array is [3, 6, 8, 11, 1, 3, 12, 15, and we set three pointers lo, mid, and high to achieve logical sub array partitioning) so the extra array required is 4 + 4 = 8. The process of merging can be summarized briefly as follows:

1 Copy the elements from the two copiedarray to the new array, and take the example mentioned above, Copiedarray = [3, 6, 8, 11, 1, 3, 12, 15];

2 set two pointers to the corresponding first element in the atomic array, assuming that the two pointers are named Leftidx and Rightidx, then Leftidx = 0 (the first element in the corresponding Copiedarray [3]), Rightidx = 4 (corresponds to the CO The fifth element in the Piedarray [1]);

3 compares the values of the array elements that LEFTIDX and Rightidx point to. Select the smaller one and assign its value to the corresponding position in the original array I, after the assignment, respectively, to participate in the assignment of these two indexes do 1 operations, if LEFTIDX or Rigthidx value has reached the end of the corresponding array Tail, the remaining elements of the array can only be copy to the rest of the element in order.

Here's a concrete example of a merge:

First trip: 
 
Auxiliary Array [21, 28, 39 | 35, 38] (the array is split into about two sub arrays, separated by |)  
 
[, , &NB Sp , , ] (first 21 compared to 35, the left sub array wins, LEFTIDX = 0, i = 0)  
 
Second trip: 
 
Auxiliary array 38] 
 
[28, , , ] (second 28 compared to 35, left sub array wins, LEFTIDX = 1, I = 1  
 
Third: [35, , 38] ,
 
[, ] (third time 39 and 3 5 comparison, the right side of the array wins, RIGHTIDX = 0, i = 2)  
 
Fourth: [] , UTC,,
 
[21, 28, 38, ] (fourth time 39 vs. 38, the right sub array wins, RIGHTIDX = 1, i = 3)  
 
Fifth: [P, P, 38]  br>  
[21, 28, 35, 38, 39] (the fifth time the right sub array has been copied, no need to compare LEFTIDX = 2, i = 4)
The above is a merge process, we can do the entire need to sort the array to do a finite split (each Divided into two, until the length of the decimal group of 1, length of 1 o'clock array has not been sorted. After this, in reverse order (because of recursion), the arrays are merged until the last time a N/2 is merged, and the array sort is completed after the merge completes.

The additional space required for the merge sort is the largest of all sorts, and each merge requires the same elements as the sum of the two array lengths that participate in the merge (in order to provide a secondary array). You can infer that the space complexity of the merge sort is 1 + 2 + 4 + ... + N = n * (n + 2)/4 (ignoring the parity of N), time complexity is more difficult to estimate, the younger brother also forget how much (embarrassed).

Implementation code:

Copy Code code as follows:



/**


* Merge Sorting


*/


MERGE (new sortable () {


Public &lt;t extends comparable&lt;t&gt;&gt; void sort (t[) array, Boolean ascend) {


This.sort (array, 0, array.length–1, ascend);


}





Private &lt;t extends comparable&lt;t&gt;&gt; void sort (t[] array, int lo, int hi, boolean ascend) {


OPTIMIZE One


If the substring ' s length is less than 20,


Use insertion sort to reduce recursive invocation


if (Hi–lo &lt; 20) {


for (int i = lo + 1; I &lt;= hi; i++) {


T Toinsert = Array[i];


int j = i;


for (; j &gt; lo; j–) {


int compare = Array[j-1].compareto (Toinsert);


if (compare = 0 | | Compare &lt; 0 = ascend) {


Break


}


ARRAY[J] = array[j-1];


}





ARRAY[J] = Toinsert;


}





Return


}





int mid = lo + (hi–lo)/2;


Sort (Array, lo, Mid, ascend);


Sort (Array, mid + 1, hi, ascend);


Merge (Array, lo, Mid, Hi, ascend);


}





Private &lt;t extends comparable&lt;t&gt;&gt; void merge (t[] array, int lo, int mid, int hi, boolean ascend) {


OPTIMIZE Two


If it is already to right, skip this merge


Since there ' s no need to doing so


int leftendcomparetorigthstart = Array[mid].compareto (Array[mid + 1]);


if (leftendcomparetorigthstart = 0 | | Leftendcomparetorigthstart &lt; 0 = ascend) {


Return


}





@SuppressWarnings ("Unchecked")


T[] Arraycopy = (t[]) new Comparable[hi-lo + 1];


System.arraycopy (Array, lo, arraycopy, 0, arraycopy.length);





int lowidx = 0;


int highidx = Mid–lo + 1;





for (int i = lo; I &lt;= hi; i++) {


if (Lowidx &gt; Mid–lo) {


Left sub Array exhausted


Array[i] = arraycopy[highidx++];


else if (Highidx &gt; Hi–lo) {


Right sub array exhausted


Array[i] = arraycopy[lowidx++];


else if (Arraycopy[lowidx].compareto (Arraycopy[highidx]) &lt; 0 = ascend) {


Array[i] = arraycopy[lowidx++];


} else {


Array[i] = arraycopy[highidx++];


}


}


}


})

6. Quick Sort

The fast sort is also a "divide and conquer" sorting algorithm implemented by merging method, its charm is that it can at each partition (the core of the sorting algorithm) can be for an array element to determine the final correct position of the order (once positioned, the next cycle will not consider this element).

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.