【发布时间】:2016-10-28 23:01:28
【问题描述】:
我正在尝试在一副纸牌上实现不同的排序算法。我已经使用枚举实现了一个基卡类来构建西装和面孔。我的课程基于 Dietel 和 Dietel 的 Java Book。但是,我在将一副纸牌传递给我实现的排序算法时遇到了困难,因为我无法传递一个可以排序的数组。我不知道我的方法是否正确,我已经阅读了 stackexchange 上的许多帖子,其中一些建议使用 Comparable (Implementing a Deck of Cards in Java),但我看不到使用我的排序算法。请参阅 (How to Sort the Cards. (Is my code wrong?)) 和 (Implementing a Deck of Cards in Java) 和 (Java Sorting object in ArrayList)。通过让 DeckOfCards 返回一系列数字,例如1.1、1.2、1.3,我想我有一个可以排序的序列。我还阅读了关于序数的文章,但所有关于这些的 cmets 似乎都反对这种方法。感谢对此尝试的任何帮助。请注意,我已经以相同的方式实现了合并排序和选择排序,并且存在相同的问题 - 我显然在这里遗漏了一些东西!
下面是我的代码:
//卡片类
class Card
{
//public static enum Face {Ace, Deuce, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King};
public static enum Face {Ace(1), King(2), Queen(3), Jack(4), Ten(5), Nine(6), Eight(7), Seven(8), Six(9), Five(10), Four(11), Three(12), Deuce(13);
int rank;
Face(int r){ rank = r;}
int getRank() {return rank;}
}
//public static enum Suit {Clubs, Diamonds, Hearts, Spades };
public static enum Suit {Spades(1), Hearts(2), Diamonds(3), Clubs(4);
int order;
Suit(int o){ order = o;}
int getOrder() {return order;}
}
private final Face face; // face of card
private final Suit suit; // suit of card
// two-argument constructor
public Card( Face cardFace, Suit cardSuit )
{
face = cardFace; // initialize face of card
suit = cardSuit; // initialize suit of card
}
// return face of the card
public Face getFace() { return face;}
// return suit of Card
public Suit getSuit() { return suit;}
// return String representation of Card
public String toString()
{
//return String.format( "%s.%s", suit.getOrder(), face.getRank() );
return String.format( "%s.%s", suit, face );
}
}
// class DeckOfCards declaration
public class DeckOfCards
{
private List< Card > list; // declare List that will store Cards
// set up deck of Cards and shuffle
public DeckOfCards()
{
Card[] deck = new Card[ 52 ];
int count = 0; // number of cards
// populate deck with Card objects
for ( Card.Suit suit : Card.Suit.values() )
{
for ( Card.Face face : Card.Face.values() )
{
deck[ count ] = new Card( face.getRank(), suit.getOrder() );
count++;
}
}
list = Arrays.asList( deck ); // get List
//Collections.shuffle( list ); // shuffle deck
}
// output deck
public void printCards()
{
// display 52 cards in two columns
for ( int i = 0; i < list.size(); i++ )
System.out.printf( "%-20s%s", list.get( i ),
( ( i + 1 ) % 2 == 0 ) ? "\n" : "" );
}
public static void main( String[] args )
{
DeckOfCards cards = new DeckOfCards();
cards.printCards();
//cards.InsertionSort();
}
}
//插入排序
public static void insertionSort(DeckOfCards[] listToSort)
{
for (int i = 0; i < listToSort.length-1; i++)
{
for (int k = i+1; k>0; k--)
{
if(listToSort[k] < listToSort[k-1]) //Code breaks here
{
swap(listToSort, k, k-1);
}
else
{
break;
}
print(listToSort);
}
}
}
【问题讨论】:
-
你可以使用
Collections.sort -
@4castle “我正在尝试实现不同的排序算法”,“我的班级”。似乎使用现有的排序方法不是 OP 在这里寻找的。span>