简体   繁体   English

如何使用可比性对数组进行排序?

[英]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()? 如何使用compareTo()对我的Integer数组值进行排序?

This will do: Arrays.sort(intArray). 这样做: 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}; 其中aInteger[] a = {1, 3, 2, 7, 9, 11};

Are you trying to do by hand what Arrays.sort(Object[]) does? 您是否要手工完成Arrays.sort(Object[])工作? 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. 然后,您真正需要的是一本有关算法的书,然后您应该研究各种实现:冒泡,插入,快速,Shell,堆等。Java有自己的算法,在某个地方进行了说明。

However, you should not be using generic types since you know you are using Integer . 但是,您不应该使用泛型类型,因为您知道自己正在使用Integer You know you have Integer , so use it. 您知道您有Integer ,所以使用它。 Integer implements Comparable , so there's no need for the extra declaration. Integer实现Comparable ,因此不需要额外的声明。

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. 如果你想测试使用的算法,则更换sortObject方法。 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. 除非有人为Comparable定义了一个单独的子类,并且仅将排序应用于该子类的实例,否则不能重写Comparable元素的各个compareTo()方法。

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. 对于一般的Comparable类型,在每次排序时重写Comparator类的compare()方法都可以访问数组组件的compareTo()方法。 Here is a quick implementation using Java inheritance and an option to do the sorting in ascending or descending order: 这是一个使用Java继承的快速实现,并提供了按升序或降序进行排序的选项:

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: 使用intArray值运行上面的静态sort()方法,就像ArraySorter类的main()方法一样,将产生以下输出:

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) . 当然,上述结果(按升序排列)与仅调用Arrays.sort(intArray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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