【问题标题】:Java Selection Sort, what is wrong with my code? [closed]Java选择排序,我的代码有什么问题? [关闭]
【发布时间】:2016-02-03 23:43:41
【问题描述】:
import java.util.Random;

public class Tester {
    public static void main(String[] args) {
        selectionSort(args);
    }

    private static void printArray(int[] anArray) {
        for (int i = 0; i < anArray.length; i++) {
            if (i > 0) {
                System.out.print(", ");
            }
            System.out.print(anArray[i]);
        }
    }


    public static void selectionSort(String[] args) {

        int i, x = 0;

        int l = 10;
        Random r = new Random(271);
        int array[] = new int[l];
        for (i = 0; i < l; i++) {
            array[i] = r.nextInt();
        }

        while (i < l) {

            for (int j = 1; j <= i; j++) {
                if (array[j] < array[x])
                    x = j;
            }

            i++;
        }
        printArray(array);
    }

}

一切都很好,我只是无法正确打印。当我打印时,我得到“-1061221096、-349834974、-1279215928、1452441141、-367008517、638966200、-464597014、1551135748、-446923224、542496703”,这是不正确的。我相信每个数字都应该在 271 以下。

【问题讨论】:

  • 您的意见是什么?你为什么将args 传递给selectionSort 方法?
  • 没有输入,我应该只得到输出。我想将 (int[] arr) 传递给选择排序,但是我遇到了错误。
  • Random 有一个内部种子和算法,要求您对一组值使用单个实例,使用多个实例可以生成重复值甚至相同顺序的值

标签: java selection-sort


【解决方案1】:

尝试替换这个:

 Random r = new Random(271);

与:

 Random r = new Random();

然后替换这个:

 array[i] = r.nextInt();

与:

 array[i] = r.nextInt(271);

您可以在271 下输出类似这样的内容:

  18, 94, 189, 105, 32, 153, 68, 159, 178, 34

【讨论】:

  • 谢谢。如果可以的话,请给这个评分,我的业力在 15 岁以下。
【解决方案2】:

你有电话

Random r = new Random(271);

现在,每次我使用 Random 时,我都会这样做

Random r = new Random();
int rand = r.nextInt(271);

这应该可以按预期工作。

仅从代码清理的角度来看,您不需要将args[] 传递给selectionSort()。您可以简单地使该方法没有参数并且不从主方法传递任何内容。

【讨论】:

  • 谢谢你,请给这个人打分,因为我的业力还不到 15 岁。
【解决方案3】:
while (i < l){
    for(int j=1; j<=i; j++){
        if(array[j] < array[x])
            x = j;
    }

    i++;}

这段代码不会被调用,因为'i'等于'l',因为之前的循环。 271 被称为种子,它不会给你小于 271 的随机数,为了生成小于 271 的数字,你应该使用 r.next(271) 参见 API 文档 Random API JSE7

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多