Java Fundamentals Hardening 56: Merging and sorting of classical algorithms (mergesort)

Source: Internet
Author: User

1. The principle of merge sorting:

Principle, the original array is divided into several sub-arrays, each sub-array is sorted,

Continue to merge the array with the sub-arrays, and the merge remains orderly until all are merged, forming an ordered array

Example:

Unordered Array [6 2 4 1 5 9]

Look at the status of each step, and then look at the merge details.

First step: [6 2 4 1 5 9] original state

Step Two: [2 6] [1 4] [5 9] 22 merge Sort, sort details behind introduction

Step three: [1 2 4 6] [5 9] Continue two groups of merging

Fourth step: [1 2 4 5 6 9] Merge complete, sort complete

Output result: [1 2 4 5 6 9]

2. Merge Sort Code implementation:

1  PackageCn.itcast;2 3 /*4 * Merge operation (merge), also called merge algorithm, refers to the operation of merging two sorted sequences into a sequence. 5 * If there is a series {6,202,100,301,38,8,1}6 * Initial state: [6] [202] [100] [301] [38] [8] [1] comparison times7 * I=1 [6 202] [301] [8] [1] 38 * i=2 [6 202 301] [1 8] 49 * i=3 [1 6 8 202 301] 4Ten  */ One  Public classMergeSort { A      Public Static voidSortint[] data) { -         int[] temp =New int[data.length]; -MergeSort (data, temp, 0, data.length-1); the     } -  -     Private Static voidMergeSort (int[] Data,int[] temp,intLintr) { -         intMid = (L + r)/2; +         if(L = =R) -             return; + mergesort (data, temp, l, mid); AMergeSort (data, temp, MID + 1, R); at  -          for(inti = l; I <= R; i++) { -Temp[i] =Data[i]; -         } -         intI1 =l; -         intI2 = mid + 1; in          for(intcur = l; Cur <= R; cur++) { -             if(I1 = = Mid + 1) toData[cur] = temp[i2++]; +             Else if(I2 >R) -Data[cur] = temp[i1++]; the             Else if(Temp[i1] <Temp[i2]) *Data[cur] = temp[i1++]; $             ElsePanax Notoginseng  -Data[cur] = temp[i2++]; the         } +     } A}

Java Fundamentals Hardening 56: Merging and sorting of classical algorithms (mergesort)

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.