Reputation: 7
lets say i have a string array of shuffled cards
HK C2 C8 CQ S3 SJ S4 D2 HQ H9 HT DT ST
H2 H3 SA CA HJ S9 S6 S8 H8 H6 C7 D7 CJ
H7 C9 DQ DA C5 D4 D6 D9 SK DJ CK DK SQ
D5 HA D3 S2 H4 S5 C3 D8 CT S7 C6 C4 H5
How do i custom sort them into
S2 S3 S4 S5 S6 S7 S8 S9 ST SJ SQ SK SA
H2 H3 H4 H5 H6 H7 H8 H9 HT HJ HQ HK HA
D2 D3 D4 D5 D6 D7 D8 D9 DT DJ DQ DK DA
C2 C3 C4 C5 C6 C7 C8 C9 CT CJ CQ CK CA
Currently I have tried, Arrays.sort(stringArray)
method and i end up with
C2 C3 C4 C5 C6 C7 C8 C9 CA CJ CK CQ CT
D2 D3 D4 D5 D6 D7 D8 D9 DA DJ DK DQ DT
H2 H3 H4 H5 H6 H7 H8 H9 HA HJ HK HQ HT
S2 S3 S4 S5 S6 S7 S8 S9 SA SJ SK SQ ST
After that, i tried to do an insertion method but ended up with
ST SQ SK SJ SA S9 S8 S7 S6 S5 S4 S3 S2
HT HQ HK HJ HA H9 H8 H7 H6 H5 H4 H3 H2
DT DQ DK DJ DA D9 D8 D7 D6 D5 D4 D3 D2
C2 C3 C4 C5 C6 C7 C8 C9 CA CJ CK CQ CT
This is what I've done so far
Arrays.sort(stringArray);
for (j = 13; j < stringArray.length; j++) {
String key = stringArray[j];
i = j - 1;
while (i >= 0) {
if (key.compareTo(stringArray[i]) < 0) {
break;
}
stringArray[i + 1] = stringArray[i];
i--;
}
stringArray[i + 1] = key;
}
EDIT: So i have to sort these elements in the following order: S,H,D,C Also, it must be according to the rank of the cards. Thus,
S2,S3,S4,S5,S6,S7,S8,S9,ST,SJ,SQ,SK,SA
Upvotes: 0
Views: 131
Reputation: 40034
Another way would be to represent each card as a String and three numbers or other values depending on your requirements.
class Card {
String name; // eg. AS, TD, 5H
int rank; // 0 - 12
int suit; // 0 - 3
int value; // card rank 0 - 51. rank and suit could be set using mod and div.
public int getCardValue() {
return value;
}
// other getters added here
// ...
public String toString() {
return name;
}
}
Then you can just sort on the value using natural ordering (or some other ordering). Assuming they are in a deck of type List of Card.
Collection.sort(deck, Comparator.comparing(Card::getCardValue));
Upvotes: 0
Reputation: 13123
Java Collections
has a sort()
method that takes both the collection to be sorted and a comparator. The comparator is a class with a method that takes two items of the type you are sorting and returns an indicator whether the first is less than, equal to, or greater than the other according to whatever rules it would like.
Put your items in a Java Collection, write your comparator, and let Java handle the sorting algorithm.
Upvotes: 1