简体   繁体   中英

How can I sort array using comparable?

Consider I have this:

class Sort {

private Integer[] intArray = {30,20,50,100,1,2,6,1,3,5};

Sort() {

    sortObject(intArray);
}

 public <T extends Comparable<T>> void sortObject(T[] array) {

    T el = array[0];

    for(T elements : array) {
        if(el.compareTo(elements)<0) {
            /// ??????
        }        

    }

How can I sort my Integer array values using compareTo()?

This will do: Arrays.sort(intArray).

if you want to do reverse sort ie sort in descending order than do as below:

Arrays.sort(a, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2-o1;
        }
    });

where a is Integer[] a = {1, 3, 2, 7, 9, 11};

Are you trying to do by hand what Arrays.sort(Object[]) does? Then, what you really need is a book on algorithms, and then you should look at the various implementations: bubble, insertion, quick, Shell, heap, etc. Java has its own algorithm which it documents somewhere.

However, you should not be using generic types since you know you are using Integer . You know you have Integer , so use it. Integer implements Comparable , so there's no need for the extra declaration.

class SortExample {

    private Integer[] intArray = {30,20,50,100,1,2,6,1,3,5};

    SortExample() {
        System.out.println("Before sort " + Arrays.toString(intArray));
        sortObject(intArray);
        System.out.println("After  sort " + Arrays.toString(intArray));
    }

    public void sortObject(Integer[] array) {
        Arrays.sort(intArray);
    }

}

If you want to test an algorithm you use, replace the sortObject method. For bubble sort, use this:

// Figure out how efficient your algorithm is.
private int numberSwaps = 0;

public void sortObject(Integer[] array) {
    final int last = array.length - 1;
    for (int end = last; end > 0; end--) {
        for (int i = 1; i <= end; i++) {
            // No need for compareTo here; it does exactly the same thing.
            if (array[i] < array[i-1]) {
                swap(array, i, i-1);
                numberSwaps++;
            }
        }
    }
    System.out.println("Needed " + numberSwaps + " swaps.");
}

private void swap(Integer[] array], int from, int to) {
    int temp = array[from];
    array[from] = array[to];
    array[to] = temp;
}

The individual compareTo() method of the Comparable elements cannot be overriden, unless one defines a separate subclass to Comparable and only applies the sorting to instances of that subclass.

For a generic Comparable type, overriding of the compare() method of the Comparator class on every sorting, provides access to the compareTo() method of the array components. Here is a quick implementation using Java inheritance and an option to do the sorting in ascending or descending order:

import java.util.Arrays;
import java.util.Comparator;

public class ArraySorter
{
    private ArraySorter()
    {
    }

    public static <T extends Comparable<T>> void sort(
        final T[] array, final boolean ascending)
    {
        Arrays.sort(array, new Comparator<T>()
        {
            @Override
            public int compare(T o1, T o2)
            {
                return (ascending?o1.compareTo(o2):o2.compareTo(o1));
            }
        });
    }

    public static void main(String[] args)
    {
        Integer[] intArray = {30,20,50,100,1,2,6,1,3,5};

        System.out.println("UNSORTED:   " + Arrays.asList(intArray));

        ArraySorter.sort(intArray, true);

        System.out.println("ASCENDING:  " + Arrays.asList(intArray));

        ArraySorter.sort(intArray, false);

        System.out.println("DESCENDING: " + Arrays.asList(intArray));
    }
}

Running the static sort() method above using the intArray value, as the main() method of the ArraySorter class does, the following output is produced:

UNSORTED:   [30, 20, 50, 100, 1, 2, 6, 1, 3, 5]
ASCENDING:  [1, 1, 2, 3, 5, 6, 20, 30, 50, 100]
DESCENDING: [100, 50, 30, 20, 6, 5, 3, 2, 1, 1]

Of course, the above result, for ascending order, is identical to just calling Arrays.sort(intArray) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM