I need to know how to sort an array of Strings, I know how to do a selection sort, however I have BOTH numbers and letters in the array. The idea is to sort a hand of cards.
You can use String::charAt(int) to retrieve the characters at positions 0 and 1 and use those to compare.
Use a Comparator,
then the Arrays.sort()
method. This should help with your coding as it lets you focus on a single thing: how do I order 2 different cards? You will have to hard-code in the ordering somehow, here is one way to do it. I haven't tested it; and it only sorts based on the first character. If the first characters are the same, then you should look at the second charater.
import java.util.Comparator;
public class CardComparator implements Comparator<String> {
private static final List<Character> CARD_ORDER = Arrays.asList(
'A', 'K', 'Q', 'J', '1', '9', '8', '7', '6', '5', '4', '3', '2');
@Override
public int compare(String card1, String card2) {
if( card1.equals(card2)) {
return 0;
}
int firstIndex = CARD_ORDER.indexOf(card1.charAt(0));
int secondIndex = CARD_ORDER.indexOf(card2.charAt(0));
return firstIndex - secondIndex;
}
}
Use Collections to do this for you. A sorted collection like a TreeMap will sort as you fill it. Collections with a sort method can be sorted after loading.
If you need a custom sort order, you can provide your own Comparator. Arrays allow you to provide your own Comparator. TreeMaps can be created with a Comparator.
If you create your a class you wish to be sortable you should implement the Comparable interface.
Have a look at this great link related to array sorting: http://www.leepoint.net/notes-java/data/arrays/70sorting.html Arrays class has few static methods very useful maybe some of them suit your needs.