归并排序

package cn.aust.zyw.demo;

/**
 * Created by zyw on 2016/2/15.
 */
public class MergeSort2 {
    public static void main(String args[]){
        int a[]={3,2,5,6,1,7,4};
        mergeSort(a);
        for(int i=0;i<a.length;i++){System.out.print(a[i]+" ");}
    }
    public static void mergeSort(int[] array) {
        sortArray(array, 0, array.length - 1);
    }
    //merge合并
    public static void merge(int a[],int low,int mid,int high){
        int i=low;
        int m=mid+1;
        int k=0;
        int temp[]=new int[high-low+1];
        while(i<=mid&&m<=high){
            if(a[i]>a[m]){
                temp[k++]=a[m++];
            }else{
                temp[k++]=a[i++];
            }
        }
while (i<=mid){ temp[k++]=a[i++]; } while (m<=high){ temp[k++]=a[m++]; } for(k=0,i=low;i<=high;i++,k++){ a[i]=temp[k]; } } //sortArray分组 public static void sortArray(int[] array, int start, int end) { if (start == end) { return; } int sortSize = end - start + 1; int seperate; if (sortSize % 2 == 0) { seperate = start + sortSize / 2 - 1; } else { seperate = start + sortSize / 2; } sortArray(array, start, seperate); sortArray(array, seperate + 1, end); merge(array, start, seperate, end); } }
原文地址:https://www.cnblogs.com/yunwuzhan/p/5191420.html