【问题标题】:How to selection sort a list of array objects by the value of an array objects如何按数组对象的值对数组对象列表进行选择排序
【发布时间】:2021-12-20 11:33:20
【问题描述】:

我有一个学生列表,我想使用选择排序算法对其进行排序。我想根据名字、年龄和 id 对学生列表进行排序。我的学生班是一个 POJO 班,只有 getter 和 setter。它有 4 个实例变量 - firstName、lastName、age 和 id。

下面是我的代码-

private static void selectionSort(Student[] list, String key) {
    for (int i = 0; i< list.length - 1; i++) {
        int min_index = i;
        for (int j = i+1; j < list.length; j++) {
            // TO-DO for each of the unsorted elements
            // if element < currentMinimum
            if (list[j].compareTo(list[min_index])) {
                // TO-DO
            }
        }
    }
}

这里的list参数是Student对象的列表。我在这里传递关键参数,它可以是名字或 id 或年龄。

我的交换方法如下-

private static void swap(Students[] list, int index1, int index2) {
    Student temp = list[index1];
    list[index1] = list[index2];
    list[index2] = temp;
}

我这样调用我的方法-

selectionSort(list, "firstName");

selectionSort(list, "id");

selectionSort(list, "age");

我不确定如何比较每个未排序元素的嵌套循环中的值。我尝试使用 compareTo 但它给了我错误。我试图在不使用 compareTo() 的情况下实现这一点。

【问题讨论】:

    标签: java data-structures selection-sort


    【解决方案1】:

    compareTo 方法不返回boolean,而是返回int。它返回 1、0 或 -1。

    • 1:更大
    • -1:少
    • 0:相等

    你可以通过foo.compareTo(boo) &lt; 0实现你想要的;

    【讨论】:

      【解决方案2】:

      我对这个问题提出了两种不同的方法。如果您正在做家庭作业或类似的事情并且您不想使事情复杂化,您可以选择第一种方法。不建议对类的字段名称进行硬编码,但因为您正在寻找一种通过名称获取字段值的方法:

      解决方案1: “不推荐用于生产代码”

      比较器:

          public static Integer compareTwoStudents(Student student1, Student student2, String field) throws NoSuchFieldException {
              switch (field) {
                  case "id":
                      return student1.getId().compareTo(student2.getId());
                  case "name":
                      return student1.getName().compareTo(student2.getName());
                  case "age":
                      return student1.getAge().compareTo(student2.getAge());
                  default:
                      throw new NoSuchFieldException();
              }
          }
      

      排序算法:

              public static void selectionSort(Student[] list, String key) {
              for (int i = 0; i < list.length - 1; i++) {
                  int minElementIndex = i;
                  for (int j = i + 1; j < list.length; j++) {
                      if (compareTwoStudents(list[minElementIndex], list[j], key) > 0) {
                          minElementIndex = j;
                      }
                  }
                  if (minElementIndex != i) {
                      Student temp = list[i];
                      list[i] = list[minElementIndex];
                      list[minElementIndex] = temp;
                  }
              }
          }
      

      “解决方案 2” 使用泛型,您可以定义一个泛型 getter 方法和一个泛型比较器,如下所示:

      通用吸气剂:

          private static <T> Field getField(Class<T> clazz, String fieldName) {
              try {
                  return clazz.getDeclaredField(fieldName);
              } catch (java.lang.NoSuchFieldException e) {
                  throw new RuntimeException(e);
              }
          }
      

      通用比较器:

          public static <T> Comparator<T> getGenericComparatorLambda(Class<T> clazz,
                                                                     String fieldName) {
              final Field field = getField(clazz, fieldName);
              field.setAccessible(true);
              Comparator<T> orderByComparator = (f1, f2) -> {
                  Comparable compA, compB;
                  try {
                      compA = (Comparable) field.get(f1);
                      compB = (Comparable) field.get(f2);
                  } catch (IllegalAccessException e) {
                      throw new RuntimeException(e);
                  }
                  return Objects.compare(compA, compB, Comparator.naturalOrder());
              };
              return orderByComparator;
          }
      

      排序算法:

          public static void selectionSort(Student[] list, String key) {
              for (int i = 0; i < list.length - 1; i++) {
                  int minElementIndex = i;
                  for (int j = i + 1; j < list.length; j++) {
                      if (getGenericComparatorLambda(Student.class, key).compare(list[minElementIndex], list[j]) > 0) {
                          minElementIndex = j;
                      }
                  }
                  if (minElementIndex != i) {
                      Student temp = list[i];
                      list[i] = list[minElementIndex];
                      list[minElementIndex] = temp;
                  }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-01
        • 1970-01-01
        • 2020-07-11
        相关资源
        最近更新 更多