Merge Sort

来源:互联网 发布:现在有什么网络歌曲 编辑:程序博客网 时间:2024/05/20 01:38

The main idea of merge sort is:

  1. Divide array into two halves
  2. Recursively sort each half
  3. Merge two half

    The purpose of Merge operation is “Given two sorted sub arrays a[lo] to a[mid] and a[mid+1] to a[hi], replace the sorted subarray a[lo] to a[hi]”

So The Merger Operation is as following:

public static void merge(int[] a, int[] aux, int lo, int mid, int hi){        // a[lo ... mid] and a[mid ... hi] have been sorted        for(int k=lo;k<=hi;k++){            aux[k] = a[k];  //copy all the element in a to array-aux        }        int i = lo;        int j = mid+1;        // i scans the first array, j scans the second; k scans the whole        for(int k=lo;k<=hi;k++){            if(i>mid) a[k] = aux[j++];            else if(j>hi) a[k] = aux[i++];            else if(aux[j]<aux[i]) a[k] = aux[j++];            else a[k] = aux[i++];        }    }

The Sort Operation is :

// This is easy to understand, sort the first half, afterwards sort the second half. At last, merge them togetherpublic void sort(int[] a, int[] aux, int lo, int hi){        if(hi <= lo) return;        int mid =lo + (hi - lo) / 2;        sort(a,aux,lo,mid);        sort(a,aux,mid+1,hi);         merge(a,aux,lo,mid,hi);    }

Test case:

public class sort {    public static void main(String[] args){        int[] a = {1,9,5,7,3,0,6,2,4,13,16,15};        int[] aux = new int[a.length];        merge m = new merge();        m.sort(a,aux,0,a.length-1);        for(int i=0;i<a.length; i++){        System.out.print(a[i]+" ");    }    }// result: 0 1 2 3 4 5 6 7 9 13 15 16}
0 0
原创粉丝点击