Java选择排序,我的代码出了什么问题?

时间:2016-02-03 23:43:42

标签: java selection-sort

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

}

一切都很好我只是无法正确打印。当我打印时,我得到&#34; -1061221096,-349834974,-1279215928,1452441141,-367008517,638966200,-464597014,1551135748,-446923224,542496703&#34;这是不正确的。我相信每个数字应该低于271。

3 个答案:

答案 0 :(得分:2)

尝试替换它:

$(EXECUTABLES): %: %.o
    $(CC) $< -o $@ $(LDFLAGS) $(LD_LIBS)

使用:

 Random r = new Random(271);

并替换它:

 Random r = new Random();

使用:

 array[i] = r.nextInt();

您可以在 array[i] = r.nextInt(271); 下输出类似内容:

271

答案 1 :(得分:1)

你有一行

Random r = new Random(271);

现在,每次我使用Random,我总是用

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

这应该按预期工作。

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

答案 2 :(得分:0)

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