2.3.17哨兵。修改算法2.5,去掉内循环while中的边界检查。由于切分元素本身就是一个哨兵(v不可能小于a[lo]),左侧边界的检查是多余的。要去掉另一个检查,可以在打乱数组后将数组的最大元素放在a[length-1]中。该元素永远不会移动(除非和相等的元素交换),可以在所有包含它的子数组中成为哨兵。注意:在处理内部子数组时,右子数组中最左侧的元素可以作为左子数组右边界的哨兵。
public class E2d3d17
{
public static void sort(Comparable[] a)
{
StdRandom.shuffle(a);
exch(a,maxIndex(a),a.length-1);
sort(a,0,a.length-1);
}
public static int maxIndex(Comparable[] a)
{
int max=0;
for(int i=1;i<a.length;i++)
{
if(less(a[max],a[i])) max=i;
}
return max;
}
private static void sort(Comparable[] a,int lo,int hi)
{
if (hi<=lo) return;
int j=partition(a,lo,hi);
sort(a,lo,j-1);
sort(a,j+1,hi);
}
private static int partition(Comparable[] a,int lo,int hi)
{
int i=lo,j=hi+1;
Comparable v=a[lo];
while(true)
{
while(less(a[++i],v)); //if(i==hi) break;
while(less(v,a[--j]));// if(j==lo) break;
if(i>=j) break;
exch(a,i,j);
}
exch(a,lo,j);
return j;
}
private static boolean less(Comparable v,Comparable w)
{ return v.compareTo(w)<0;}
private static void exch(Comparable[] a,int i,int j)
{
Comparable t=a[i];
a[i]=a[j];
a[j]=t;
}
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(args[0]);
sort(a);
assert isSorted(a);
show(a);
}
}
public class E2d3d17
{
public static void sort(Comparable[] a)
{
StdRandom.shuffle(a);
exch(a,maxIndex(a),a.length-1);
sort(a,0,a.length-1);
}
public static int maxIndex(Comparable[] a)
{
int max=0;
for(int i=1;i<a.length;i++)
{
if(less(a[max],a[i])) max=i;
}
return max;
}
private static void sort(Comparable[] a,int lo,int hi)
{
if (hi<=lo) return;
int j=partition(a,lo,hi);
sort(a,lo,j-1);
sort(a,j+1,hi);
}
private static int partition(Comparable[] a,int lo,int hi)
{
int i=lo,j=hi+1;
Comparable v=a[lo];
while(true)
{
while(less(a[++i],v)); //if(i==hi) break;
while(less(v,a[--j]));// if(j==lo) break;
if(i>=j) break;
exch(a,i,j);
}
exch(a,lo,j);
return j;
}
private static boolean less(Comparable v,Comparable w)
{ return v.compareTo(w)<0;}
private static void exch(Comparable[] a,int i,int j)
{
Comparable t=a[i];
a[i]=a[j];
a[j]=t;
}
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(args[0]);
sort(a);
assert isSorted(a);
show(a);
}
}