归并排序-java实现

归并排序的代码和思路整理很多。这里我只做整理。易理解的图、思路清晰的代码

1:归并排序图解过程如下:以数组{50,10,90,30,70,40,80,60,20}为例,

Java实现如下:

package cn.itpcc.sort;

import java.util.Arrays;
//归并排序是一种比较占内存,但却效率高且稳定的算法
public class MergeSort {
    public static void main(String[] args) {
        int a[] ={51,32,73,85,99,4,2};
        megesort(a,0,a.length-1);
        System.out.println("排序结果"+Arrays.toString(a));
    }

    public static void merge(int a[], int low ,int mid ,int high){
       // System.out.println("低位"+low);
       // System.out.println("高位"+high);
        int [] temp =new int [high-low+1];
        int i =low;     //左指针
        int j =mid+1;   //右指针
        int k =0 ;
        while(i<=mid&&j<=high){
            if(a[i]<a[j]){
                temp[k++]=a[i++];
            }else {
                temp[k++]=a[j++];
            }
        }
        //把左边剩余的数移入数组
        while(i<=mid){
            temp[k++]=a[i++];
        }
        //把右边剩余的数移入数组
        while(j<=high){
            temp[k++]=a[j++];
        }
        //把新数组中的数覆盖nums数组
        for(int k2 =0;k2<temp.length;k2++){
            a[k2+low]=temp[k2];
        }
    }

    public static void megesort(int a [],int low ,int high){
       int mid =(high+low)/2;
       if(low<high){
           //归并排序的思想 刚开始分割 然后两两归并,到就近的两个
          megesort(a,low,mid);
          megesort(a,mid+1,high);
          merge(a,low,mid,high);
       }
    }
}

                                                                                                     一别两宽 各生欢喜

猜你喜欢

转载自blog.csdn.net/CentOS_Pc/article/details/82892735