1

I am trying to write a simple sort function that can sort data of any type using the Comparable interface. I think I have done that, but I am having problems passing arrays of specific types as arguments. The code is

public class Main {
    public static void main(String[] args) {
        int[] arr= {12,14,11,6};
            // The above gives error
            // But this works : Comparable[] arr= {12,14,11,6};
        Comparable b[]= Selection.sort(arr);
        for (Comparable x:b)
            System.out.println(x);
    }
}

What is the probelm ? The error reads : Comparable is a raw type. References to generic type Comparable<T> shoulb be parameterized.

Just to make it more clear, the remaining code is:

public class Selection {

    public static Comparable[] sort(Comparable[] a){
        int N= a.length;

        for(int i=0;i<N;i++){
            int min=i;
            for(int j=i+1;j<N;j++)
                if(less(a[j],a[min]))
                    min=j;

            exch(a,i,min);
        }
        return a;
    }

    // Other methods defined here
}

1 Answer 1

3

If they are comparable, don't reinvent the wheel!

Arrays.sort(b);

You could wrap it in your method:

public static Comparable[] sort(Comparable[] a){
    Arrays.sort(a);
    return a;
}

But you are adding no value. Just use Arrays.sort(array); where you need it.


If you want to preserve the original array, then make a copy first, also using the Arrays utility class:

Comparable[] sorted = Arrays.copyOf(array);
Arrays.sort(sorted);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.