归并排序——MergeSort实现(Java)

蓝咒 提交于 2020-03-02 17:52:57

根据大佬们的一些构思和做法,自己实现了归并算法,总体利用递归实现,空间消耗的还是比较大,mergesort方法的空间复杂度就在O(N).

package 数据结构_排序;

public class 归并排序{
    public static void main(String[] args) {
        int[] arr = {1,8,36,5,2,4,6};
        MergeSort sort = new MergeSort();
        sort.mergeSort(arr,0,arr.length-1);
        for(int i : arr){
            System.out.print(i+" ");
        }
    }
}

class MergeSort{
    /**
     *
     * @param a  add a list of need sort
     * @param start  where you start sorting
     * @param end  where you end sorting
     */
    public void mergeSort(int[] a,int start,int end){
    //当拆分至最后一个停止拆分,否则递归拆分
        if(start < end){
            int mid = (start+end)/2;
            mergeSort(a,start,mid);
            mergeSort(a,mid+1,end);
            //拆分完毕之后进行排序合并
            merge(a,start,mid,end);
        }
    }

    /**
     *
     * @param a    to add two list
     * @param left  the first list of start
     * @param mid   the middy of between a and b list
     * @param right  the second list of end
     */
    public void merge(int[] a,int left,int mid,int right){
    //中间变量数组
        int[] temp = new int[a.length];
        //三个指针变量,依次指向左子序列,右子序列头;新建数组定义从左子序列头开始,
        int p1 = left,p2 = mid+1,k = left;
		//序列指针不达上线,依次比较左右子序列中的值(左右序列皆为有序,即使只有一个数,)
        while(p1 <= mid && p2 <= right){
        //哪一序列的值小,依次插入新序列
            if(a[p1] <= a[p2])
                temp[k++] = a[p1++];
            else
                temp[k++] = a[p2++];
        }
		//将剩余的有序序列依次插入即可
        while (p1 <= mid)  temp[k++] = a[p1++];
        while (p2 <= right)  temp[k++] = a[p2++];
		//把原始的乱序序列替换成有序序列		
        for (int i = left;i <= right;i++){
            a[i] = temp[i];
        }
    }
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!