美文网首页
归并排序

归并排序

作者: uin_sisyphus | 来源:发表于2018-10-31 17:05 被阅读0次
    image.png image.png

    空间复杂度O(n),时间复杂度O(nlog(n))

        public static void mergeSort(int[] a, int low, int high){
            if(low < high){
                int mid = (low+high)/2;
                //左排序
                mergeSort(a, low, mid);
                //右排序
                mergeSort(a, mid+1, high);
                //合并
                merge(a, low,mid,high);
            }
        }
    
        private static void merge(int[] a, int low, int center, int high) {
            int[]tempArr = new int[a.length];
            int mid = center +1;//右数组
            int temp = low;//左数组
            int third = low;//临时数组
            while(low <= center && mid<= high){
                //比较两个数组,谁小取谁
                if(a[low] <= a[mid]){
                    tempArr[third++] = a[low++];
                }else{
                    tempArr[third++] = a[mid++];
                }
            }
            //左剩余,全部加进去
            while(low <= center){
                tempArr[third++] = a[low++];
            }
            //右剩余,全部加进去
            while(mid <= high){
                tempArr[third++] = a[mid++];
            }
            //临时数组给原始数组赋值
            while(temp <= high){
                a[temp] = tempArr[temp];
                temp++;
            }
        }
    

    相关文章

      网友评论

          本文标题:归并排序

          本文链接:https://www.haomeiwen.com/subject/wqwatqtx.html