Selection Sorting String Arrays (Java)

前端 未结 4 926
情歌与酒
情歌与酒 2020-12-20 01:18

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.

相关标签:
4条回答
  • 2020-12-20 01:28

    You can use String::charAt(int) to retrieve the characters at positions 0 and 1 and use those to compare.

    0 讨论(0)
  • 2020-12-20 01:41

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-20 01:46

    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.

    0 讨论(0)
  • 2020-12-20 01:53

    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.

    0 讨论(0)
提交回复
热议问题