1

The function tries to transform the array into a pendulum form. Like the input is:

1 3 2 5 4

The answer should be:

5 3 1 2 4

The minimum is in between.

public static void printPendulum(int[] arr, int n){
    Arrays.sort(arr);
    int noOfRotations = n/2;
    for(int i=0;i<noOfRotations;i++){
        int temp = arr[n-1];
        for(int j=n-1;j>0;j--){
            arr[j] = arr[j-1];
        }
        arr[0] = temp;
    }
    int temparr[] = new int[noOfRotations-1];
    for(int i=0;i<noOfRotations-1;i++)
        temparr[i] = arr[i];
    Comparator<Integer> comp = Collections.reverseOrder();     
    Arrays.sort(temparr, comp);
    for(int i=0;i<noOfRotations-1;i++)
        arr[i] = temparr[i];
    for(int i=0;i<n;i++)
        System.out.print(arr[i] + " ");
    System.out.println();     
}

The compilation error is as follows:

    prog.java:36: error: no suitable method found for sort(int[],Comparator<Integer>)
        Arrays.sort(temparr, comp);
              ^
    method Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) is not applicable
      (inference variable T#1 has incompatible bounds
        equality constraints: int
        upper bounds: Integer,Object)
    method Arrays.<T#2>sort(T#2[],int,int,Comparator<? super T#2>) is not applicable
      (cannot infer type-variable(s) T#2
        (actual and formal argument lists differ in length))
  where T#1,T#2 are type-variables:
    T#1 extends Object declared in method <T#1>sort(T#1[],Comparator<? super T#1>)
    T#2 extends Object declared in method <T#2>sort(T#2[],int,int,Comparator<? super T#2>)
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • Possible duplicate of [Java Array Sort descending?](https://stackoverflow.com/questions/1694751/java-array-sort-descending) – jhamon Apr 17 '18 at 13:36

2 Answers2

3

Use

Integer temparr[] = new Integer[noOfRotations-1];

instead

int temparr[] = new int[noOfRotations-1];
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
xingbin
  • 27,410
  • 9
  • 53
  • 103
3

There is no signature with a Comparator for arrays of primitives.

For instance, the signatures for an int[] array are:

sort(int[] a)
sort(int[] a, int fromIndex, int toIndex)

The one you are trying to use looks like:

sort(T[] a, Comparator<? super T> c)

So you need to pass an Integer[], not an int[]:

Integer[] boxedArray = Arrays.stream(temparr).boxed().toArray(Integer[]::new);
Arrays.sort(boxedArray, comp);
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142