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