This code will sort string array and return a new arraylist with order word (ascending), but ordered done from end of each word. This code work like sorting file name in file manager.
Source code:
public class WordC {
// sort from end to begin
public static void main(String[] args) {
String[] sTest = {"4H", "5H", "8C", "8D", "9H", "9D", "AC", "6S", "5D", "6D", "KD", "10C", "AD" };
for (int i=0;i<13;i++) {
System.out.print(sTest[i]+" ");
}
System.out.println();
System.out.println("Sorting");
ArrayList<String> tmp = sortEnd2Begin(sTest);
tmp.forEach((String myCard) ->{
System.out.print(myCard+" ");
});
System.out.println();
}
private static ArrayList<String> sortEnd2Begin(String[] myCards) {
ArrayList<String> myNewCards = new ArrayList<>();
myNewCards.add(myCards[0]);
for (int i=1;i<myCards.length;i++) {
// loop for unordered myCards
String card2Sort = myCards[i];
for (int j=0;j<myNewCards.size();j++) {
// loop for ordered myNewCards
// find until card2Sort equal or bigger then existing list
String cardIterate = myNewCards.get(j);
int iterMax = card2Sort.length();
if (card2Sort.length() > cardIterate.length()) {
iterMax = cardIterate.length();
}
int posCard = beforeOrAfter(card2Sort, cardIterate, 0, iterMax);
if (posCard==0 || posCard<0) {
myNewCards.add(j, card2Sort);
break;
} else {
// TODO
//System.out.println(j); // debug
if (j+1==myNewCards.size()) {
// end of list
myNewCards.add(card2Sort);
break;
}
}
}
}
return myNewCards;
}
// -1 wordA before wordB
// 0 wordA equal wordB
// 1 wordA after wordB
private static int beforeOrAfter(String wordA, String wordB, int iterX, int iterMax) {
//System.out.println(wordA+" "+wordB+" "+iterX+" "+iterMax);
int inA = wordA.length()-1-iterX;
int inB = wordB.length()-1-iterX;
char cA = wordA.charAt(inA);
char cB = wordB.charAt(inB);
int retValue = 0;
if (iterX+1==iterMax) {
// we reach max recursive {
//System.out.println(iterX+" "+iterMax+" "+cA+" "+cB); // debug
if (cA==cB) {
//System.out.println("Debug"); // debug
if (wordA.length()<wordB.length()) {
retValue = -1;
} else if (wordA.length()>wordB.length()) {
retValue = 1;
} else {
retValue = 0; // equal letters and length
}
} else if (cA<cB) {
//retValue = -1; // ori
} else if (cA>cB) {
retValue = 1; // ori
}
} else {
if (cA<cB) {
//System.out.println(cA+" < "+cB+" "+(cA < cB)); // debug
retValue = -1; // ori
} else if (cA>cB) {
//System.out.println(cA+" > "+cB+" "+(cA > cB)); // debug
retValue = 1; // ori
} else {
//System.out.println(cA+" = "+cB+" "+(cA == cB)); // debug
retValue = beforeOrAfter(wordA, wordB, iterX+1, iterMax);
}
}
return retValue;
}
}