经典算法-归并排序

版权声明: https://blog.csdn.net/wangzhonglinqwe/article/details/79952857

先明白merge,单单2个数组的排序算法;然后在写递归条件以及调用处理

package jvm;

public class Main {
    public static void merge(int[] a , int first ,int mid ,int last ,int[] temp ) {
        /*if(first == last)
            return;*/
        int i ,j;
        for(i= first,j= mid +1;first<=mid &&j<=last;i++ ) {
            if(a[first]>=a[j]) temp[i] = a[first++];
            else temp[i] = a[j++];
        }
        while(first < mid ) temp[i++] = a[first++];
        while(j < last ) temp[i++] = a[j++];
    }

    public static void mergesort(int[] a,int first ,int last ,int[] temp) {
        if(first < last)//判定出栈的条件
        {
            int mid = (first+last)/2;
            mergesort(a,first,mid,temp);
            mergesort(a,mid+1,last,temp);
            merge(a, first, mid, last, temp);
        }
    }

    public static void main(String[] args) {
        int[] a = {1,2,3,10,23,41,532,21};
        int[] temp = new int[a.length];
        if(a.length == 0)
            return;
        mergesort(a, 0, a.length, temp);
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页