Algorithm (4th edition)-2.2 merge sort

Source: Internet
Author: User
Tags comparable sorts

Merge: Merges two ordered arrays into a larger, ordered array.

Merge algorithm: first (recursively) divide it into two halves, and then merge the results together.

· Advantages: It is guaranteed that the time required to sort the array of arbitrary length n is proportional to the nlogn;

· Disadvantage: The extra space required is proportional to n.

Abstract method of 2.2.1 in situ merging

     Public Static voidMerge (comparable[] A,intLointMidinthi) {        //will A[lo. Mid] and A[mid+1..hi] Merge        inti = lo, j = mid + 1;  for(intK = lo; K <= Hi; k++) {//will A[lo. Hi] Copy to Aux[lo. Hi]AUX[K] =A[k]; }         for(intK = lo; K <= Hi; k++) {            if(i > Mid) a[k] = aux[j++];//left half exhausted            Else if(J > Hi) a[k] = aux[i++];//The right half is exhausted            Else if(Less (Aux[j], aux[i])) a[k] = aux[j++];//Right < left            ElseA[K] = aux[i++];//Right > Left        }    }
Merge

2.2.2 Top to bottom merge sort

 Public classMerge {Private StaticComparable[] aux;//merging the required auxiliary arrays     Public Static voidsort (comparable[] a) {aux=NewComparable[a.length];//Disposable Space AllocationSort (A, 0, a.length-1); }    Private Static voidSort (comparable[] a,intLointhi) {        //A[lo the array: Hi] Sort        if(Hi <= lo)return; intMid = lo + (Hi-lo)/2;                Sort (A, lo, mid); //sort the left halfSort (A, mid + 1, HI);//sort the right halfMerge (A, lo, Mid, hi);//Merge Results    }     Public Static voidMerge (comparable[] A,intLointMidinthi) {        //will A[lo. Mid] and A[mid+1..hi] Merge        inti = lo, j = mid + 1;  for(intK = lo; K <= Hi; k++) {//will A[lo. Hi] Copy to Aux[lo. Hi]AUX[K] =A[k]; }         for(intK = lo; K <= Hi; k++) {            if(i > Mid) a[k] = aux[j++];//left half exhausted            Else if(J > Hi) a[k] = aux[i++];//The right half is exhausted            Else if(Less (Aux[j], aux[i])) a[k] = aux[j++];//Right < left            ElseA[K] = aux[i++];//Right > Left        }    }    Private Static BooleanLess (comparable V, comparable W) {returnV.compareto (W) < 0; }    Private Static voidExch (comparable[] A,intIintj) {comparable T=A[i]; A[i]=A[j]; A[J]=T; }    Private Static voidShow (comparable[] a) {//to print an array in a single line         for(inti = 0; i < a.length; i++) Stdout.print (A[i]+ " ");    Stdout.println (); }     Public Static Booleanissorted (comparable[] a) {//test array elements for order         for(inti = 1; i < a.length; i++)            if(Less (A[i], a[i-1]))return false; return true; }     Public Static voidMain (string[] args) {//reads strings from standard input, sorts them, and outputsString[] A =in.readstrings ();        Sort (a); assertissorted (a);    Show (a); }}
Merge

1. The sort () method actually works by arranging the correct order of multiple merge () method calls.

2. for any array of length n, the top-down merge sort requires a 1/2nlgn to NLGN comparison, which requires access to the array 6NlgN times.

3. We may also significantly shorten the run time of the merge sort by the following methods:

· Using insert sorting for small-scale sub-arrays

· Tests whether an array is ordered

· Do not copy elements to a secondary array

2.2.3 Bottom-up merge sort

ImportJava.lang.Math; Public classMergebu {Private StaticComparable[] aux;//merging the required auxiliary arrays     Public Static voidsort (comparable[] a) {//LGN Times 22 merges        intN =a.length; Aux=NewComparable[n];  for(intSZ = 1; SZ < N; SZ = sz +sz) for(intLo = 0; Lo < N-sz; Lo + = sz +sz) Merge (A, lo, lo+ sz-1, Math.min (lo + sz + sz-1, N-1)); }     Public Static voidMerge (comparable[] A,intLointMidinthi) {        //will A[lo. Mid] and A[mid+1..hi] Merge        inti = lo, j = mid + 1;  for(intK = lo; K <= Hi; k++) {//will A[lo. Hi] Copy to Aux[lo. Hi]AUX[K] =A[k]; }         for(intK = lo; K <= Hi; k++) {            if(i > Mid) a[k] = aux[j++];//left half exhausted            Else if(J > Hi) a[k] = aux[i++];//The right half is exhausted            Else if(Less (Aux[j], aux[i])) a[k] = aux[j++];//Right < left            ElseA[K] = aux[i++];//Right > Left        }    }    Private Static BooleanLess (comparable V, comparable W) {returnV.compareto (W) < 0; }    Private Static voidExch (comparable[] A,intIintj) {comparable T=A[i]; A[i]=A[j]; A[J]=T; }    Private Static voidShow (comparable[] a) {//to print an array in a single line         for(inti = 0; i < a.length; i++) Stdout.print (A[i]+ " ");    Stdout.println (); }     Public Static Booleanissorted (comparable[] a) {//test array elements for order         for(inti = 1; i < a.length; i++)            if(Less (A[i], a[i-1]))return false; return true; }     Public Static voidMain (string[] args) {//reads strings from standard input, sorts them, and outputsString[] A =in.readstrings ();        Sort (a); assertissorted (a);    Show (a); }}
Mergebu

1. The first thing we do is 22 merge (think of each element as an array of size 1), then 44 merge (two arrays of 2 size into an array of 4 elements), then 88 merge, go on. In each merge, the second sub-array of the last merge may be smaller than the first subarray (but this is not a problem for the merge () method), and if not, the size of the two arrays should be the same in all merges, and the next round of neutron arrays will be doubled in size.

2. For any array of length n, the bottom-up merge sort requires a 1/2nlgn to NLGN comparison, which requires access to the array 6NlgN times.

· When the array length is a power of 2, the top-down and bottom-up merge sorts use the same number of comparisons and groups of accesses, except in the order of the sequence;

· Other times, the comparison of the two methods and the order of the group accesses will vary.

3. The bottom-up merge sort is more suitable for data organized with the linked list.

The complexity of 2.2.4 sorting algorithm

1. No comparison-based algorithm can guarantee less than LG (n!) ~NLGN A comparison to sort an array of length n.

The best case is at least LG (n!), worst case at least NLGN.

2. The worst-case comparison of merge sorting and the minimum number of comparisons required for any comparison-based sorting algorithm are ~NLGN.

Algorithm (4th edition)-2.2 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.