说说你会如何将一副扑克牌排序,限制条件是只能查看最上面的两张牌,交换最上面的两张牌,或是将最上面的一张牌放到这摞牌的最下面。
思路:模仿冒泡排序
冒泡排序是移动i(即数组指针),而我们可以通过移动数组来近似实现
我们可以固定交换前两个,移动数组
package Cap2_1;import edu.princeton.cs.introcs.StdIn;
import edu.princeton.cs.introcs.StdOut;
import edu.princeton.cs.introcs.StdRandom;public class Test extends Shell{public static void sortX(Comparable[] a){int N = a.length;while(!isSorted(a)){for(int j=0;j<N-1;j++){if(less(a[1], a[0])) { exch(a, 0, 1); //第一张和第二张交换}for(int z=0;z<N-1;z++) exch(a, z, z+1); //第一张放到最后}for(int z=0;z<N-1;z++) exch(a, z, z+1);}}public static void main(String[] args) {for(int i=0;i<10;i++){int N = 10+i*10;Integer[] a = new Integer[N];for(int j=0;j<N;j++)a[j] = (int)(StdRandom.random()*N);StdRandom.shuffle(a);sortX(a);
// show(a);assert Shell.isSorted(a);}}
}