'this function should do sorting by relative difference with the integer K {k=7 like [3,6,9] _->[6,9,3]} but its not working
this function should do sorting by relative difference with the integer K {k=7 like [3,6,9] _->[6,9,3]} but its not working
static void sortABS(int arr[], int n,int k)
{
List al = Arrays.asList(arr);
Comparator<Integer>com=(a,b)->
{
return Math.abs(a-k)-Math.abs(b-k) ;
};
Collections.sort(al,com);
for(int i=1;i<al.size();i++)
System.out.print(al.get(i)+"");
}
Solution 1:[1]
Arrays.asList(arr); returns a List of int[]. That means Collections.sort doesn't do anything, because its input contains only one element.
The result printing for-loop at the end is implemented incorrectly, because its index starts at 1 instead of 0. It's also unnecessary, because you can just pass the list al directly to System.out.print.
The parameter int n is unnecessary/unused too.
static void sortABS(int arr[], int k) {
List<Integer> al = Arrays.stream(arr).boxed().collect(Collectors.toList());
Comparator<Integer> com = (a, b) -> {
return Math.abs(a - k) - Math.abs(b - k);
};
Collections.sort(al, com);
System.out.print(al);
}
If you want to avoid the array-to-list conversion and sort the array directly, then you have to use Integer instead of int.
static void sortABS(Integer arr[], int k) {
Comparator<Integer> com = (a, b) -> {
return Math.abs(a - k) - Math.abs(b - k);
};
Arrays.sort(arr, com);
System.out.print(Arrays.toString(arr));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
