2.2.20间接排序。编写一个不改变数组的归并排序,它返回一个int[]数组perm,其中perm[i]的值是原数组中第i小的元素的位置。
public class E2d2d20
{
private static int subArrayLenTrunONInsertionSort=15;
public static int[] sort(Comparable[] a)
{
int len=a.length;
int[] perm=new int[len];
int[] aux=new int[len];
for(int i=0;i<len;i++)
{
perm[i]=i;
aux[i]=i;
}
sort(perm,aux,a,0,a.length-1);
return perm;
}
private static void sort(int[] perm,int[] aux,Comparable[] a,int lo,int hi)
{
if ((hi-lo+1)<=subArrayLenTrunONInsertionSort)
{
insertionSort(perm,a,lo,hi);
}
else
{
int mid=lo+(hi-lo)/2;
sort(aux,perm,a,lo,mid);
sort(aux,perm,a,mid+1,hi);
if(!less(a[aux[mid+1]],a[aux[mid]]))
{
for(int i=lo;i<=hi;i++)
perm[i]=aux[i];
return;
}
merge(aux,perm,a,lo,mid,hi);
}
}
private static void merge(int[] perm,int[] aux,Comparable[] a,int lo,int mid,int hi)
{
int i=lo;
int j=mid+1;
for(int k=lo;k<=hi;k++)
{
if (i>mid) aux[k]=perm[j++];
else if (j>hi) aux[k]=perm[i++];
else if (less(a[perm[j]],a[perm[i]])) aux[k]=perm[j++];
else aux[k]=perm[i++];
}
}
private static boolean less(Comparable v,Comparable w)
{ return v.compareTo(w)<0;}
private static void exch(int[] perm,int i,int j)
{
int t=perm[i];
perm[i]=perm[j];
perm[j]=t;
}
private static void insertionSort(int[] perm,Comparable[] a,int lo,int hi)
{
for (int i=lo+1;i<=hi;i++)
for (int j=i;j>lo && less(a[perm[j]],a[perm[j-1]]);j--)
exch(perm,j,j-1);
}
public static boolean isSorted(int[] perm,Comparable[] a)
{
for(int i=1;i<a.length;i++)
if(less(a[perm[i]],a[perm[i-1]])) return false;
return true;
}
public static void main(String[] args)
{
Integer N=Integer.parseInt(args[0]);
Comparable[] a=new Comparable[N];
for(int i=0;i<N;i++)
a[i]=StdRandom.uniform();
int[] perm=sort(a);
StdOut.println("Sorted="+isSorted(perm,a));
}
}