Small Orange Book Reading Guide (v)--two implementations of merge sort

Source: Internet
Author: User

Algorithm Description: Merging two smaller, ordered arrays into a larger, ordered array is a relatively easy thing to do. We only need to compare the leftmost element in the same order, and then alternately put in the new array. This is the implementation of the top-down merge sort. Unlike the previous algorithm, the merge sort requires additional storage space, and the space-for-time approach is also a frequently needed choice in the sorting algorithm.

Algorithm diagram:

Algorithm interpretation: A larger array is continuously divided into smaller two arrays, until it can no longer be segmented and then reverse merge, and then merge the process of adjusting the order. The difficulty of merging algorithms is how to reduce the use of additional storage space as much as possible.

Java code example:

 Packagealgorithms.sorting;Importalgorithms. sortable;ImportAlgorithms.common.ArraysGenerator;Importjava.util.Arrays; Public classMergeImplementsSortable<integer> {    Privateinteger[] aux; @Override Public voidsort (integer[] array) {aux=NewInteger[array.length]; Sort (Array,0, Array.length-1); }    Private voidSort (integer[] array,intLointhi) {        //Recursive End Condition        if(Hi <=lo) {            return; }        intMid = lo + (Hi-lo)/2;        Sort (Array, lo, mid); Sort (array, mid+ 1, HI);    Merge (Array, lo, Mid, hi); }    Private voidMerge (integer[] array,intLointMidinthi) {        inti =Lo; intj = Mid + 1; //the Aux array is a member variable with the same length as the array. Reuse to conserve storage space.          for(intindex = lo; Index <= Hi; ++index) {Aux[index]=Array[index]; }         for(intindex = lo; Index <= Hi; ++index) {            //if the low array is exhausted , the high-order array is copied sequentially            if(I >mid) {Array[index]= aux[j++]; }            //if the high-level array is exhausted , the low-level array is copied sequentially            Else if(J >hi) {Array[index]= aux[i++]; }            //If the leftmost element of the high-level array is smaller than the left-most element, the leftmost element of the high array is copied            Else if(Aux[j] <Aux[i]) {Array[index]= aux[j++]; }            //If the leftmost element of the low array is less than or equal to the leftmost element of the high array, the leftmost element of the low array is copied            Else{Array[index]= aux[i++]; }        }    }     Public Static voidMain (string[] args) {integer[] array= Arraysgenerator.generate (10, 0, 100); Merge Merge=NewMerge ();        Merge.sort (array);    System.out.println (arrays.tostring (array)); }}

Qt/c++ code Example:

#include "merge.h"Merge::merge () {}merge::~Merge () {if(aux) {delete aux; }}voidMerge::sort (int*arr,intLen) {    if(aux) {delete aux; } aux=New int[Len]; Sort (arr,0, Len-1);}voidMerge::sort (int*arr,intLointhi) {    if(Hi <=lo) {        return; }    intMid = lo + (Hi-lo)/2;    Sort (arr, lo, mid); Sort (arr, mid+ 1, HI); Merge (arr, lo, Mid, HI);}voidMerge::merge (int*arr,intLointMidinthi) {    intLoindex = lo;//Low array start coordinates    intHiindex = mid + 1;//high-level array in fact coordinates//Copying an array     for(inti = lo; I <= hi; ++i) {Aux[i]=Arr[i]; }     for(inti = lo; I <= hi; ++i) {if(Loindex >mid) {Arr[i]= aux[hiindex++]; }        Else if(Hiindex >hi) {Arr[i]= aux[loindex++]; }        Else if(Aux[hiindex] <Aux[loindex]) {Arr[i]= aux[hiindex++]; }        Else if(Aux[loindex] <=Aux[hiindex]) {Arr[i]= aux[loindex++]; }    }}

The dynamic diagram of the top-down merge sort algorithm:

The dynamic diagram of the bottom-up merge sort algorithm:

Algorithm explanation: First adjusts array[i] and array[i+1] to 1 for step size, then array[2*i] and array[2*i+1] until the first round of the entire array is completed. Next, adjust array[i],array[i+1] and array[2*i],array[2*i+1] by 2 for stride length until the second round of the entire array is completed.

Java code example:

 Packagealgorithms.sorting;Importalgorithms. sortable;ImportAlgorithms.common.ArraysGenerator; Public classMergebuImplementsSortable<integer> {    Privateinteger[] aux; @Override Public voidsort (integer[] array) {aux=NewInteger[array.length];  for(intlen = 1; Len < Array.Length; Len = 2 * len) {//length of sub-array selected each time             for(intLo = 0; Lo < Array.length-len; Lo + = 2 *Len) {merge (array, lo, lo+ len-1, Math.min (lo + (2 * len)-1, array.length-1)); }        }    }    Private voidMerge (integer[] array,intLointMidinthi) {        intLoidx =Lo; intHiidx = mid + 1;  for(inti = lo; I <= hi; ++i) {Aux[i]=Array[i]; }         for(inti = lo; I <= hi; ++i) {if(Loidx >mid) {Array[i]= aux[hiidx++]; } Else if(Hiidx >hi) {Array[i]= aux[loidx++]; } Else if(Aux[hiidx] <Aux[loidx]) {Array[i]= aux[hiidx++]; } Else{Array[i]= aux[loidx++]; }        }    }     Public Static voidMain (string[] args) {integer[] array= arraysgenerator.generate (1000, 0, 9999); Mergebu Mergebu=NewMergebu ();        Mergebu.sort (array); System.out.println (Arraysgenerator.issort (Array,"ASC")); }}

Qt/c++ code example (slightly)

There are a lot of explanations for algorithmic efficiency, but according to my own test merge algorithm is currently the highest ranking algorithm.

RELATED links:

Algorithms for Java

Algorithms for Qt

Small Orange Book Reading Guide (v)--two implementations of 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.