2.2.12

question:

Sublinear extra space. Develop a merge implementation that reduces the extra space requirement to max(M,N/M), based on the following idea: Divede the array into N/M blocks of size M (for simplicity in this description, assume that N is a multiple of M). Then, (i) considering the blocks as items with their first key as the sort key, sort them using selection sort; ans (ii) run through the array merging the first block with the second, then the second block with the third, and so forth.

answer:

//这道题不是很理解题目意思,我是先把这N/M个块先块内排完序,再把块两个两个归并成大块,再归并大块,直到排序完成

import edu.princeton.cs.algs4.*;

public class Merge
{
     public static void insertionsort(Comparable[] a, int lo, int hi)//插排数组a[]的lo到hi
    {
        for(int i = lo+1; i <= hi; i++)
        {
            for(int j = i; j > 0 && less(a[j], a[j-1]); j--)
                exch(a, j, j-1);
        }
    }
    
    private static void exch(Comparable[] a, int i, int j)
    {
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
    
    private static Comparable[] aux;
    
    public static void merge(Comparable[] a, int lo, int mid, int hi)
    {
        int i = lo, j = mid + 1;
        
        for(int k = lo; k <= hi; k++)//复制
            aux[k] = a[k];
    
        for(int k = lo; k <= hi; k++)//把a[]填满就退出循环
        {
            if(i > mid)//左侧已用完,则只能从右侧拿
                a[k] = aux[j++];
            else if(j > hi)//右侧已用完,则只能从左侧拿
                a[k] = aux[i++];
            else if(less(aux[i], aux[j]))//当前左侧比右侧小,从右侧拿
                a[k] = aux[i++];
            else//反之当前右侧比左侧小,从左侧拿
                a[k] = aux[j++];
        }
    }
    
    public static void sort(Comparable[] a)
    {
        int N = a.length;
        aux = new Comparable[N];
        int M = 4;//我随便取了个M=4
        for(int i = 0; i < N; i+=M)//分块插排
        {
            insertionsort(a,i,Math.min(i+M-1,N-1));//这里取min就不用假设a的size是M的整数倍了
        }
        
        for(int sz = M; sz < N; sz+=sz)//每次merge的大小size,从1开始到小于N的最大size
            for(int lo = 0; lo < N-sz; lo += sz+sz)//左sz和右sz进行归并,所以lo+=2sz
            merge(a, lo, lo+sz-1, Math.min(lo+sz+sz-1, N-1));//取min是怕最后边界的那个lo+sz+sz-1超过数组大小N-1,防止数组越界
    }
    
    private static boolean less(Comparable v, Comparable w)
    {
        return v.compareTo(w) < 0;
    }
    
    private static void show(Comparable[] a)
    {
        for(int i = 0; i < a.length; i++)
            StdOut.print(a[i] + " ");
        StdOut.println();
    }
    
    public static boolean isSorted(Comparable[] a)
    {
        for(int i = 1; i < a.length; i++)
            if(less(a[i], a[i-1])) return false;
        return true;
    }
    
    public static void main(String[] args)
    {
        String[] a = In.readStrings();//CTRL + d
        sort(a);
        assert isSorted(a);
        show(a);
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9122315.html