Java Sorting Algorithm _ 006 Merge Sorting

Source: Internet
Author: User
Package WZS. Sort; import java. util. arrays; // merge sort (merge), also called merge Algorithm The operation that combines two sorted sequences into one. The Merge Sorting Algorithm depends on the merge operation. Public class mergingsort {public static void main (string [] ARGs) {int A [] = {10, 3, 5, 7, 9, 1, 4, 2, 6, 8}; sort (A, 0,. length-1); system. out. println ("\ n after sorting:" + arrays. tostring (a);} public static void sort (INT [] data, int left, int right) {If (left <right) {// locate the intermediate index int center = (left + right)/2; // recursive sort (data, left, center) on the left array ); // recursive sort (data, center + 1, right) for the right array; // merge Merge (data, left, center, right );}} public static void merge (INT [] data, int left, int center, int right) {int [] tmparr = new int [data. length]; int mid = center + 1; // index of the middle array of the third record int third = left; int TMP = left; while (left <= center & Mid <= right) {// extract the smallest value from the two arrays and put it into the intermediate array if (data [left] <= data [Mid]) {tmparr [third ++] = data [left ++];} else {tmparr [third ++] = data [Mid ++];} // The remaining parts are sequentially placed in the middle array while (mid <= right) {tmparr [third ++] = data [Mid ++];} while (left <= center) {tmparr [third ++] = data [left ++];} // copy the content in the intermediate array back to the original array while (TMP <= right) {data [TMP] = tmparr [TMP ++];} system. out. println (arrays. tostring (data ));}}

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.