Java implementation Merge sort algorithm

Source: Internet
Author: User

First, decomposition: the sequence of n elements to be sorted is decomposed into two sub-sequences, each of which consists of N/2 elements.

Second, governance: Call merge sort mergesort for each subsequence, and perform recursive operations

Third, merging: Merging two ordered sub-sequences to produce sorted results.

Code from Codego.net:

 public static void MergeSort (int[] A, int[] tmp, int left, int. right) {    if (left < right) {      INT mid = left + (right-left)/2;       MergeSort (A, TMP, left, mid),///To sort       mergesort (A, TMP, MID + 1, right);//Sort &NB Sp     Merge (A, TMP, left, Mid + 1, right);//around merge    }  } public static void merge (Int[] A, int[] TMP, int left, int rightpos,       int right) {    int leftend = rightPos-1;     in T tmppos = left;     int num = right-left + 1;     while (left <= leftend && rightpos <= right) {      if (A[left] < A[RIGHTPO S]) {        tmp[tmppos++] = a[left++],      } else {        TMP [tmppos++] = a[rightpos++];      }    }     while (left <= leftend) {      tmp[tmppos++] = A[l eft++];         while (Rightpos <= right) {      tmp[tmppos++] = a[rightpos++];   &N Bsp }     for (int i = 0; i < num; i++, right--) {      a[right] = Tmp[right];    } &N Bsp } 


Java implementation Merge sort 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.