扑克牌的出列排序

算法2.1.14 题目内容:说说你会如何将一副扑克牌排序,限制条件是只能查看最上面的两张牌,交换最上面的两张牌,或是将最上面的一张牌放到这摞牌的最下面。

思路参考

https://www.zhihu.com/question/33576203/answer/58349656

https://blog.csdn.net/qq_34446253/article/details/77917104

是一个冒泡排序的问题。

import edu.princeton.cs.algs4.StdOut;  
import java.util.Random;  
  
public class Test {  
    private int count;
    private int[] a;
    public Test(){
        Random rand = new Random();
        count = 0;
        a = new int[52];
        for(int i = 0;i < 52;i++){
            a[i] = 52;
        }
        for(int i = 0;i < 52;i++){
            int j = rand.nextInt(52);
            while(contains(j)){
                j = rand.nextInt(52);
            }
            a[i] = j;
        }
    }
    private boolean contains(int x){
        for(int i = 0;i < 52;i++){
            if(x == a[i])
                return true;
        }
        return false;
    }
    public boolean isSorted(){
        int N = a.length; 
        for(int i = 0; i < N; i++){
            if(a[i] != i)
                return false;
        }
        return true;
    }//牌的大小就赋值0-51
    public void exch(int i, int j){
        int midterm = a[i];
        a[i] = a[j];
        a[j] = midterm;
    }
    public void sortX(){  
        int N = a.length;  
        int flag = 1;
        while(flag != 0){
            flag = 0;
            for(int j=0;j<N-1;j++){  
                if(a[1] < a[0]) {    
                    exch( 0, 1);   //第一张和第二张交换  
                    count++;
                    flag ++;
                }  
                for(int z=0;z<N-1;z++) exch(z, z+1); //第一张放到最后  
                count++;
            }  
            for(int z=0;z<N-1;z++) exch(z, z+1);  
            count++;
        }  
    }
    public int showcount(){
        return count;
    }


    public static void main(String[] args) {  
        Test t = new Test();
        t.sortX();
        StdOut.printf(t.showcount()+"\n");
    }  
}  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值