Sort an array of primitives with a custom comparator and without converting to objects

前端 未结 5 1205
生来不讨喜
生来不讨喜 2021-02-07 08:07

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 †).

5条回答
  •  再見小時候
    2021-02-07 08:36

    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

提交回复
热议问题