归并排序个人理解


  将数组分解成一个个单数据,然后将临近两个数组进行对比和归并,接着将临近数组进行对比和归并,一直这么循环。直到排序完成才结束。

其算法如下:

private static void guibing(int[] a,int low,int high){
                    //中间值
                    int middle=(low+high)/2;
                    
                    //如果最小值小于中间值,那么继续分解
                    if(low<middle){
                        //左边分解
                        guibing(a,low,middle);
                        //右边分解
                        guibing(a,middle+1,high);
                        //左右归并
                        guibingSort(a,middle,low,high);
                    }
                } 
    
                public static void guibingSort(int[] a,int middle,int low,int high){
                    //生成临时数组用于保存临时变量
                    int[] temp=new int[high-low+1];
                    //左指针
                    int left=low;
                    //右指针
                    int right=middle+1;
                    //定义一个k用户表示临时数组temp下标,默认第一位0
                    int k=0;
                    //把较小的数先放入临时数组temp中
                    //当左指针小于中间值,并且右指针小于最大值时,该循环会将两边的数据进行比较,最后只剩一一个数据,要么在左指针,要么在右指针。
                    while(left<=middle&&right<=high){
                        //当左指针所对应的数小于右指针对应的数时
                        if(a[left]<=a[right]){
                            temp[k++]=a[left++];
                        }else {
                            temp[k++]=a[right++];
                        }
                    }
                    
                    
                    //如果存在左指针所指向的区域还有数据,那么放入数组最后位置。
                    while(left<=middle){
                        temp[k++]=a[left++];
                    }
                    
                    //如果存在右指针所指向的区域还有数据,那么放入数组最后位置。
                    while(right<=high){
                        temp[k++]=a[right++];
                    }
                    //最后将数据放入将要进行排序的数组中,该数组是从low开始
                    for (int k2 = 0; k2 < temp.length; k2++) {
                        a[k2 + low] = temp[k2];
                    }
                    
                }
原文地址:https://www.cnblogs.com/orchid9/p/7611882.html