使用数组进行选择排序

时间:2013-08-29 17:06:29

标签: java arrays class sorting selection-sort

我需要帮助使用选择排序对整数数组进行排序。它不会对某些原因进行排序。下面是我的demo / main。

  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]);
    }


}

3 个答案:

答案 0 :(得分:2)

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

从链接的Javadocs引用:

  

将此对象与指定的订单对象进行比较。返回一个   负整数,零或正整数,因为此对象较少   比,等于或大于指定的对象。

尝试以下更改:

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
}

答案 1 :(得分:0)

您的CompareTo功能错误。只需将其更改为:

public int compareTo(SelectionSortArray other) {
    return num.compareTo(other.num);     
}

键是-1 / 0/1返回码,而不是您正在使用的“0,1,2”。

通常,如果您要比较内置类型,则更容易委派给内置的比较运算符。

注意:要使用“num.compareTo”,您需要使用“Integer”而不是“int”。如果你想坚持使用“int”,你需要rgettman发布的解决方案。

答案 2 :(得分:0)

请注意,以及对compareTo

的更改
return Integer.compare(this.num,other.num)

实现了以简洁的方式返回您要返回的内容

public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

如果您想按照问题中列出的方式查看打印输出

System.out.format("%02d%n",ints[index].num);

或将toString()改为return String.format("%02d",num)

您可能还希望查看java.util.Arrays源代码,以便了解其他类似方法的实现情况。另外,请考虑更改您的类名,以表明它包含数字CustomNumber并封装您的类,以避免直接访问num

您的代码中另一个有趣的问题

    SelectionSortArray[] ints = new SelectionSortArray[8];
    ints[0] = new SelectionSortArray(01);
    ints[1] = new SelectionSortArray(02);
    ints[3] = new SelectionSortArray(03);
    ints[4] = new SelectionSortArray(04);
    ints[5] = new SelectionSortArray(05);
    ints[6] = new SelectionSortArray(06);
    ints[7] = new SelectionSortArray(07);
    ints[8] = new SelectionSortArray(08);//???

如果您在数字前面加0它将是一个八进制数字,允许的数字是0 - 7,因此您将看到上面的编译错误。还

    System.out.println(0123);
    System.out.println(0234);

不会打印

0123
0234

正如你(未)期待的那样!

83
156

在代码中使用八进制数时要小心。

相关问题