java - 使用数组进行选择排序

标签 java arrays class sorting selection-sort

我需要帮助使用选择排序对整数数组进行排序。由于某些原因它不会排序。下面是我的演示/主要内容。

  02 
  20 
  01 

应该是

  01 
  02 
  20

我的演示/主要:

    public static void main(String[] args) {


    SelectionSortArray[] ints = new SelectionSortArray[3];

    ints [0] = new SelectionSortArray(02);
    ints [1] = new SelectionSortArray(20);
    ints [2] = new SelectionSortArray(01);

    System.out.println("Unsorted array: ");

    for (int index = 0; index < ints.length; index++) {
        System.out.println(ints[index]);
    }


    SelectionSort.selectionSort(ints);

    System.out.println(" ");

    System.out.println("Sorted array using selection sort: ");

    for (int index = 0; index < ints.length; index++) {
        System.out.println(ints[index]);
    }


}

最佳答案

SelectionSortArray 类中的 compareTo 方法不正确。 compareTo如果当前对象小于另一个对象,方法必须返回小于零的 int,但您却让它返回 1

引用链接的 Javadocs:

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

尝试这些更改:

if (num == other.num) {
    result = 0;   // This was correct; no change here.
} else if (num < other.num) {
    result = -1;  // Changed from 1 to -1.
} else {
    result = 1;   // 1 or 2 is fine, as long as it's positive
}

关于java - 使用数组进行选择排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18516987/

相关文章:

java - 如何获取当前的 GPS 位置?

java - 使用java api创建Kafka主题,无需zookeeper

c# - 调用更改组件(标签)的父类(super class)函数

c - 如何在 C 中的整数数组中添加二次数列

c# - 跨类/控件调用 - 传递引用、使用事件或更改结构

PHP:php 找不到 include() 脚本中定义的类

java - 为什么我的数组类无法找出随机生成的数组的最小值和最大值?

Java:从 JInternalFrame 获取 Mainform 对象

c++ - 重载运算符在 C++ 中不起作用

javascript - 如何精简这段代码?通过第二个数组的共享属性 (_id) 获取数组的属性 (title)