What\'s the simplest way to sort a primitive array in Java with a custom comparator (or key) function and without converting to an array of objects (for performance †).
You can just build your own compare functions , and use one of the sort algorithms
easiest and slowest: BubbleSort ( O(N^2) ).
hardest but fastest : MergeSort( (O(Nlog(n) ) .
now in both algos you have the part that asks if A > B , in this part you should put your compare func.
boolean compare(int x, int y){
if(/* your crazy compare condition */)
return true;
else return false;
}
example in bubble sort :
procedure bubbleSort( A : list of sortable items )
repeat
swapped = false
for i = 1 to length(A) - 1 inclusive do:
/* if this pair is out of order */
if compare(A[i],A[i-1]) then // Notcie the compare instead of A[i] > A[i-1]
/* swap them and remember something changed */
swap( A[i-1], A[i] )
swapped = true
end if
end for
until not swapped
end procedure
hope this helps