如何使用通用参数为数组列表创建排序方法?

时间:2018-04-04 16:13:41

标签: java generics arraylist

我尝试使用通用参数对CD的数组列表进行排序。我有4个类:main,CD,Searching和排序。我有搜索方法可以工作,但我无法弄清楚如何修复排序方法。我正在尝试按序列号排序。

排序类

import java.util.ArrayList;

public class Sorting<T extends Comparable<T>> {
public int selectionSort(ArrayList<T> numbers, T key) {
      int i = 0;
      int j = 0;
      int indexSmallest = 0;
      int temp = 0;  // Temporary variable for swap

      for (i = 0; i < numbers.size(); ++i) {

         // Find index of smallest remaining element
         indexSmallest = i;
         for (j = i + 1; j < numbers.size(); ++j) {

            if (numbers.get(j) < numbers.get(indexSmallest)) {
               indexSmallest = j;
            }
         }

         // Swap numbers[i] and numbers[indexSmallest]
         temp = numbers.get(i);
         numbers[i]= numbers.get(indexSmallest);
         numindex= temp;
      }
   }

   public static void insertionSort(int[] numbers) {
      int i = 0;
      int j = 0;
      int temp = 0;  // Temporary variable for swap

      for (i = 1; i < numbers.length; ++i) {
         j = i;
         // Insert numbers[i] into sorted part 
         // stopping once numbers[i] in correct position
         while (j > 0 && numbers[j] < numbers[j - 1]) {

            // Swap numbers[j] and numbers[j - 1]
            temp = numbers[j];
            numbers[j] = numbers[j - 1];
            numbers[j - 1] = temp;
            --j;
         }
      }
   }



}

2 个答案:

答案 0 :(得分:2)

T extends Comparable<T>开始,您应该使用compareTo(T other)接口的Comparable函数。我会这样做:

public class Sorting {

    public static <T extends Comparable<T>> void selectionSort(List<T> numbers) {

        int indexSmallest = 0;
        for (int i = 0; i < numbers.size(); i++) {
            // Find index of smallest remaining element
            indexSmallest = i;
            for (int j = i + 1; j < numbers.size(); j++) {
                // use compareTo
                if (numbers.get(j).compareTo(numbers.get(indexSmallest)) < 0) {
                    indexSmallest = j;
                }
            }

            // EDIT: your swapping code was wrong
            // Swap numbers[i] and numbers[indexSmallest]
            T temp = numbers.get(i);
            numbers.set(i, numbers.get(indexSmallest));
            numbers.set(indexSmallest, temp);
        }
    }
}

答案 1 :(得分:-1)

在选择排序的最后一行中,您有: numIndex= temp; 我不相信numIndex存在...... 也许你的意思是 numbers.get(indexSmallest)= temp;