My Java development and learning journey ------) Java classic Sorting Algorithm merging and sorting

Source: Internet
Author: User

My Java development and learning journey ------) Java classic Sorting Algorithm merging and sorting
I. Merge SortingMerge Sorting is an effective Sorting Algorithm Based on merge operations. This algorithm is a typical application of Divide and Conquer. Merges ordered subsequences to obtain a fully ordered sequence. That is, first orders each subsequence, and then orders the subsequence segments. If two ordered tables are merged into an ordered table, it is called a two-way merge. The merging process is: Compare the sizes of a [I] And a [j]. If a [I] is less than or equal to a [j], copy the element a [I] In the first ordered table to r [k] and Add 1 to I and k respectively; otherwise, copy the element a [j] In the second ordered table to r [k], and Add 1 to j and k respectively. In this way, the loop continues until one of the ordered tables is completed, then copy the remaining elements in another ordered table to the Unit from subscript k to subscript t in r. The Merge Sorting Algorithm is implemented recursively. We first sort the subintervals [s, t] to the midpoint, then sort the left subintervals, and then sort the right subintervals, finally, merge the left and right intervals into an ordered interval [s, t] with one merge operation. II,Merge operation

3. Two-way merge algorithm 1. Basic algorithm ideas
Set two ordered sub-files (equivalent to the input heap) to the adjacent positions in the same vector: R [low .. m], R [m + 1 .. high], first merge them into a local temporary storage vector R1 (equivalent to the output heap), and then copy R1 back to R [low .. high.

(1) merging process
During the merge process, set the I, j, and p pointers, and their initial values point to the starting positions of the three record areas respectively. When merging, compare the keywords of R [I] and R [j] in sequence, and copy the records with smaller keywords to R1 [p, then add the pointer I or j of the copied record to 1 and the pointer p pointing to the copy position to 1.
Repeat this process until one of the two input sub-files has been completely copied (it may be called null ), copy the remaining records of another non-empty sub-file to R1.

(2) dynamically apply for R1
During implementation, R1 dynamically applies because the application space may be large, so it must be added to the application space for successful processing.


2. Merge Algorithms

Void Merge (SeqList R, int low, int m, int high) {// place two ordered sub-files R [low .. m) and R [m + 1 .. high] is merged into an ordered // sub-file R [low .. high] int I = low, j = m + 1, p = 0; // set the initial value RecType * R1; // R1 is the local vector, if p is defined to be faster for this type of pointer R1 = (ReeType *) malloc (high-low + 1) * sizeof (RecType); if (! R1) // Error ("Insufficient memory available! "); While (I <= m & j <= high) // when the two sub-files are not empty, the small ones are output to R1 [p] R1 [p ++] = (R [I]. key <= R [j]. key )? R [I ++]: R [j ++]; while (I <= m) // If the 1st sub-file is not empty, copy the remaining record to R1 [p ++] = R [I ++]; while (j <= high) // If the 2nd sub-files are not empty, then copy the remaining record to R1 [p ++] = R [j ++]; for (p = 0, I = low; I <= high; p ++, I ++) R [I] = R1 [p]; // copy the result back to R [low .. high]} // Merge


Iv. Merge Sorting Merge Sorting can be implemented in two ways: bottom-up and top-down. Let's talk about Top-down method (1) three steps of the divide and conquer Law
Set the current range of Merge Sorting to R [low .. high]. The three steps of division and control are as follows:
① Decomposition: splits the current interval into two parts, that is, finding the split point
② Solution: recursively sort the R [low... mid] and R [mid + 1 .. high] in two subintervals;
③ Combination: Combine the sorted two subintervals R [low .. mid] and R [mid + 1 .. high] is merged into an ordered interval R [low .. high].
Recursive termination condition: the subinterval length is 1 (a record is naturally ordered ).


(2) specific algorithms

Void MergeSortDC (SeqList R, int low, int high) {// sort the R [low... high] in two-way merging and sorting int mid using the division method; if (low
 
  
(3) the execution process algorithm of the algorithm MergeSortDC is shown in the recursive tree.
  5. Algorithm Analysis 1. Stable Merge Sorting is a stable sorting.
  2. The storage structure must be a sequential storage structure. It is also easy to implement on the linked list.
  3. For files whose length is n, the time complexity needs to be merged. The time for each merge is O (n ), therefore, the time complexity is O (nlgn) in both the best and worst cases ).
  4. spatial complexity requires an auxiliary vector to store the results of merging two ordered sub-files. Therefore, the complexity of the auxiliary space is O (n). Obviously, it is not local sorting. Note: If a single-chain table is used as the storage structure, it is easy to give the merge and sort in place.
  5. The number of comparison operations is between (nlogn)/2 and nlogn-n + 1.
  6. The number of assignments is (2 nlogn ). The spatial complexity of the merge algorithm is: 0 (n)
  7. Merge Sorting occupies memory, but it is a highly efficient and stable algorithm.
  
  6. Code Implementation
  
Public class MergeSortTest {public static void main (String [] args) {int [] data = new int [] {2, 4, 7, 5, 8, 1, 3, 6}; System. out. print ("initialization: \ t"); print (data); System. out. println (""); mergeSort (data, 0, data. length-1); System. out. print ("\ n sorted: \ t"); print (data);} public static void mergeSort (int [] data, int left, int right) {if (left> = right) return; // two-way merge // find the intermediate index int center = (left + right)/2; // recursive mergeSort (data, left, center) on the left array; // recursive mergeSort (data, center + 1, right) on the right array ); // merge (data, left, center, center + 1, right); System. out. print ("in sorting: \ t"); print (data) ;}/ *** merge the two arrays and merge the first two arrays in order, after merging, it is still ordered ** @ param data * array object * @ param leftStart * index of the first element of the Left array * @ param leftEnd * index of the last element of the Left array *@ param rightStart * index of the first element of the Right array * @ param rightEnd * index of the last element of the Right array */public static void merge (int [] data, int leftStart, int leftEnd, int rightStart, int rightEnd) {int I = leftStart; int j = rightStart; int k = 0; // temporary array int [] temp = new int [rightEnd-leftStart + 1]; // create a temporary array to store the temporary sorted array // confirm whether the two split arrays have obtained the last element while (I <= leftEnd & j <= rightEnd) {// fetch the smallest value from the two arrays and put it into the temporary array if (data [I]> data [j]) {temp [k ++] = data [j ++];} else {temp [k ++] = data [I ++];} // Add the remaining parts to the temporary array in sequence (in fact, only one of the two while are executed) while (I <= leftEnd) {temp [k ++] = data [I ++];} while (j <= rightEnd) {temp [k ++] = data [j ++];} k = leftStart; // copy the content in the temporary array to the original array // (the content in the original left-right range is copied back to the original array) for (int element: temp) {data [k ++] = element ;}} public static void print (int [] data) {for (int I = 0; I <data. length; I ++) {System. out. print (data [I] + "\ t");} System. out. println ();}}

VII. Running results

Initialization: 24758136 sorting: 24758136 sorting: 24578136 sorting: 24578136 sorting: 24571836 sorting: 24571836 sorting: 24571368 sorting: 12345678 sorting: 12345678 sorting: Sorting

========================================================== ========================================================== ============================

Author: Ouyang Peng: Welcome to repost. sharing with others is the source of progress!

Reprinted Please retain the original address: http://blog.csdn.net/ouyang_peng

========================================================== ========================================================== ============================



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.