Data structure--the realization of merging sort

Source: Internet
Author: User

Merge sort, is a kind of stable sort, uses the idea of divide and conquer, divides an array into half, sorts it separately, then merges into a new array.

The code is implemented as follows:

Import Java.util.arrays;public class MergeSort {public static int[] Sort (int[] nums, int. Low, int.) {          int mid = (low + high)/2;              if (Low < high) {//left sort (nums, low, mid);              Right sort (nums, mid + 1, high);          Merge merges Around (Nums, low, Mid, high);      } return nums;           public static void Merge (int[] nums, int. Low, int mid, Int. high) {int[] temp = new Int[high-low + 1];            int i = low;//left pointer int j = mid + 1;//right pointer int k = 0;                  Move the smaller number first to the new array while (I <= mid && J <= High) {if (Nums[i] < nums[j]) {              temp[k++] = nums[i++];              } else {temp[k++] = nums[j++];          }}//Move the left remaining number into the array while (I <= mid) {temp[k++] = nums[i++]; }//Move the remaining number in the right side into the array while (J < = high) {temp[k++] = nums[j++]; }//Overwrite the number in the new array with the Nums array for (int k2 = 0; K2 < temp.length; k2++) {nums[k2 + low] = temp[          K2]; }}//merge sort implementation public static void main (string[] args) {int[] array1 = {2, 7, 8, 3, 1,            6, 9, 0, 5, 4};          Mergesort.sort (array1, 0, array1.length-1);                  System.out.println (arrays.tostring (array1));        Int[] Array2 = {9, 1, 5, 3, 4, 2, 6, 8, 7};        Mergesort.sort (array2, 0, array2.length-1);     System.out.println (arrays.tostring (array2));   }  }


Data structure--the realization of merging sort

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: 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.