Sort within-merge sort

Source: Internet
Author: User

Basic algorithm thought: The simple can say that the original sequence is divided into two sequences, and then the two sequences are ordered sequence, and finally merge the two ordered sequences, also known as two-way merge; (in the last level of recursion to ensure that the left and right two sequences each have an element, these two elements are easy to order, Recursively, their parent sequences are easy to order, and finally the whole sequence is ordered.

 Packagesort;Importjava.io.IOException; Public classmergesort{ Public Static voidMain (string[] args) {int[] A =New int[] {20, 30, 90, 40, 70, 110, 60, 10, 100, 50, 80, 9, 8, 7, 6 }; MergeSort mergesort=Newmergesort (); mergesort. Sort (A,0, A.length-1);  for(inti:a) {System.out.println (i);} }  Public voidSort (int[] Arrays,intLeft_index,intRight_index) {if(Left_index < Right_index)//when left_index = = Right_index description is a single element, no further downward recursion{inti =Left_index;intj =Right_index;intM = (i + j)/2; Sort (arrays, I, M); Sort (arrays, M+ 1, Right_index); Merger (arrays, I, M, j);//until we find two immediate elements.}} voidMerger (int[] Array,intLeftintMidintRight ) {//merging ordered queues on the left and right sides of the same arrayinti =Left ;intm =mid;intj = mid+1;intK=0;int[] temp =New int[Right-left+1]; while(I <= m && j<=Right ) {//find the smallest element from the left and right side into the temp queueif(Array[i] <= array[j]) temp[k++] = array[i++];if(Array[i] > Array[j]) temp[k++] = array[j++]; }//I <= m description J points to the queue element has all entered temp while(I <=m) {Temp[k+ +] = array[i++];}//j<= Right Description J points to the queue element has all entered temp while(J <=Right ) {Temp[k+ +] = array[j++];}//ordinal left to right element, reset to row element for(k = 0; K < temp.length;k++) {Array[left+ K] =temp[k];} }}

Sort within-merge 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: 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.