I'm using Java to implement the Bucket Sorting. I want to sort the input array of [0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434]
and I create the buckets
as an array containing List<Double>
as it's elements, I sort every List<Double>
individually using List.sort
and concatenate them to get the result.
But Error occurs when I use the ArrayList.sort
method to sort the List
. I use a Lambda Expression as the parameter of the sort
function and get an error message from the IDE, it says Cannot infer functional interface type
.
The error comes from this line:
buckets[i].sort((double a, double b) -> (int)Math.signum(a-b));
But when I change it to
buckets[i].sort((a, b) -> (int)Math.signum(a-b));
there is no error and the code works well.
I am very confused why it can't infer? Thanks in advance.
The entire code is here:
import java.util.ArrayList;
import java.util.List;
class Solution {
void buckerSort(double[] arr, int n){
//create the buckets
List<Double>[] buckets = new ArrayList[n];
for (int i = 0; i<n; ++i){
buckets[i] = new ArrayList<Double>();
}
//add the input to the buckets
for (int i=0; i<n; ++i) {
int index = (int) arr[i] * 10;
buckets[index].add(arr[i]);
}
//sort every List individually
///////////////////////////////The error occurs here/////////////////////////////////////////
for (int i=0; i<n; ++i) {
buckets[i].sort((double a, double b) -> (int)Math.signum(a-b));
}
//concatenate
int index = 0;
for(int i = 0; i<n; i++) {
for (int j = 0; j<buckets[i].size(); j++) {
arr[index] = buckets[i].get(j);
index++;
}
}
}
public static void main(String args[])
{
double[] arr = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
int n = arr.length;
Solution s = new Solution();
s.buckerSort(arr, n);
System.out.println("Sorted array is: ");
for (int i = 0; i < n; ++i) {
System.out.print(arr[i] + " ");
}
}
}
You can use
buckets[i].sort( ( Double a, Double b ) -> (int) Math.signum( a - b ) );
instead, since a Comparator
of Double
accepts two Double
type arguments and not primitive double
arguments.
public int compare( Double a, Double b )
More importantly, you might just be looking to sort the elements naturally using Comparator.naturalOrder()
as performing a subtraction isn't a good way of comparing elements. So your code would look like -
buckets[i].sort( Comparator.naturalOrder() );