Java algorithm learning-----------------merging sorting algorithm

Source: Internet
Author: User

The adjacent elements in the array are paired with 22, sorted by the merge algorithm, forming a well-ordered sub-array of length 2 of the N/2 group, and then arranged into a sub-array of length 4, so continue until the entire array is ordered.

According to this idea, the elimination of recursive merge sorting algorithm (pseudo code) is as follows:

public class MergeSort {public static void MergeSort (Comparable[]a) {comparable[]b=new comparable[a.length];int S=1; while (s<a.length) {mergepass (a,b,s);//merge to Array bs+=s;mergepass (b,a,s);//merge to array as+=s;}} private static void Mergepass (comparable[] x, comparable[] y, int s) {//merge adjacent array of size S int i=0;while (i<=x.length-2*s) {///fit And the size of s at both ends of the adjacent Word group merge (x,y,i,i+s-1,i+s*2-1); i=i+2*s;} The remaining number of elements is less than 2sif (i+s<x.length) {merge (x, y, I, i+s-1, x.length-1);} else//Copy to Y {for (int j = i; J < X.length; J + +) {Y[j] = X[j];}}} private static void merge (comparable[] C, comparable[] D, int l, int m, int r) {//merge c[l:m] and C[m+1,r] to D[l:r]int I=1, j=m+1,k =l;while (i<=m && j<=r) {if (C[i].compareto (C[j]) <=0) {d[k++]=c[i++];} Else{d[k++]=c[j++];}} if (i>m) {for (int k2 = 0; K2 <=r; k2++) {d[k++] = C[k2];}} else{for (int k2 = 0; K2 <=m; k2++) {d[k++] = C[k2];}}}


Java Algorithm learning-----------------merge sorting algorithm

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.