数据结构——归并排序

归并排序

一:归并排序基本介绍

归并排序是利用归并的思想实现的排序方法,该算法采用经典的分治策略(分治法是指将问题先进行划分,划分成一些小问题,然后在家进行递归求解,而治的阶段则是将分的阶段得到的各答案“修补”在一起,即分而治之)。

二:规避给排序思想示意图

归并排序
归并排序先将待排序的数组进行划分,如图数组[8,4,5,7,1,3,6,2],当进行完划分之后会变成8,4,5,7,1,3,6,2单个数据。然后在进行操作,整个过程会执行array.length-1次合并操作。
在治阶段,我们需要将两个已经有序的子序列合并成一个有序序列,比如上图中最后一次合并,将[4,5,7,8],[1,2,3,6]两个数组进行合并,合并成最终的 [1,2,3,4,5,6,7,8],实现步骤如下:
治
治2

三:代码

package 排序算法;

/*
    归并排序

 */
import java.text.SimpleDateFormat;
import java.util.Date;

public class MergetSort {
    public static void main(String[] args) {
      //  int[] array = {8,4,5,7,1,3,6,2};
        int[] array = new int[80000];
        for (int i = 0; i < array.length; i++) {
            array[i] = (int)Math.random()*80000;
        }
        int[] temp = new int[array.length];
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        System.out.println(format);

        mergetSort(array,0,array.length-1,temp);

        Date date1 = new Date();
        String format1 = simpleDateFormat.format(date1);
        System.out.println(format1);

    }

    //分+合
    public static void mergetSort(int[] array,int left,int right,int[] temp){

        if (left<right){
            int mid = (left+right)/2;

            //向左分解
            mergetSort(array,left,mid,temp);
            //向右分解
            mergetSort(array,mid+1,right,temp);

            //合
            merge(array,left,mid,right,temp);
        }
    }

    //治
    /*
        array:待排序的数组
        left:数组最左边
        mid:中间数,是左边数组的最后一个
        right:右边数组的最后一个
        temp:中转数组
     */
    public static void merge(int[] array,int left,int mid,int right,int[] temp){
        int i = left;
        int j = mid+1;
        int t = 0; //作为temp数组的下标值

        //一:比较,并将数组种的元素按照顺序放到temp种
        while (i<=mid&&j<=right){
            if (array[i]<=array[j]){
                temp[t] = array[i];
                i++;
                t++;
            }else {
                temp[t] = array[j];
                j++;
                t++;
            }
        }
        //二:将左边或者右边剩余的数据整体赋值到temp种
        while (i<=mid){
            temp[t] = array[i];
            i++;
            t++;
        }

        while (j<=right){
            temp[t] = array[j];
            j++;
            t++;
        }

        //三:将数据从temp中拷贝到array中
        t = 0;  //将t置零
        int tempLeft = left;    //
        while (tempLeft<=right){
            array[tempLeft] = temp[t];
            tempLeft++;
            t++;
        }

    }

}

归并排序中主要还是理解递归调用的思想,要能够理解在左右划分数据以及在什么时候进行治的操作
划分数据时的真正步骤:
划分

发布了26 篇原创文章 · 获赞 5 · 访问量 4167
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章