Some comments already indicate that your recursive routine cannot sort on leaf nodes and expect to sort the entire list. You will have to return the accumulated rows in the collection, and then sort and print them once at the end.
More importantly, there is a good algorithm for rearranging an array in lexical order. It is used by the next_permutation library function in C ++ (which you can find for explanation), but itβs easy enough to translate it to java. You retrieve the char[] array, possibly with getCharArray , sort it with Arrays.sort and run it until it returns false.
void reverse(char[] a, int f, int l) { while(l>f) { char tmp = a[l]; a[l] = a[f]; a[f] = tmp; l--; f++; } } boolean next_permutation(char[] a) { if(a.length < 2) return false; for(int i = a.length-1; i-->0;) if(a[i] < a[i+1]) { int j=a.length-1; while(!(a[i] < a[j])) j--; char tmp=a[i]; a[i]=a[j]; a[j]=tmp; reverse(a, i+1, a.length-1); return true; } reverse(a, 0, a.length-1); return false; }
Once you understand what he is doing, just run while(next_permutation(array)) {println(array);} and thatβs all right. Note that this is very bad for arrays of more than 13 elements.
source share