仅生成正的随机数并对其进行排序

时间:2017-04-18 19:40:47

标签: java arrays

我正在尝试生成正数并按升序排序,而不使用arrays.sort

此代码询问有多少随机数,然后对它们进行排序并将其打印出来。我的代码询问了多少,并打印出比给定的少一个。

例如,当我要求2时,它只打印出一个。无法找到错误或错误。

代码

import java.util.*;

public class Sort {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("How many numbers do you want? ");
        int howMany = in.nextInt();
        int[] myArray = getRandomArray(howMany);

    }

    /* public static int bsearch(int[] arr, int key)
            {

            }*/
    public static int[] getRandomArray(int howMany) {
        int[] returnMe = new int[howMany]; // Assume size >= 0
        Random rand = new Random();
        for (int i = 0; i < howMany; i++) {
            returnMe[i] = rand.nextInt(Integer.MAX_VALUE) + 1;
            System.out.print(returnMe[i] + " ");
            for (i = 1; i <= returnMe.length; i++) {
                for (int j = i + 1; j < returnMe.length; j++) {
                    int tmp = 0;
                    if (returnMe[i] > returnMe[j]) {
                        tmp = returnMe[i];
                        returnMe[i] = returnMe[j];
                        returnMe[j] = tmp;
                    }
                }
            }
        }
        return returnMe;
    }
}

1 个答案:

答案 0 :(得分:1)

因为您要更改循环中的i

for (int i = 0; i < howMany; i++) {//loop 1
    ...
    for (i = 1; i <= returnMe.length; i++) {//loop 2
    //--------------------------------^^^
    //When you get out from this loop, the i is > then the original i

要避免此问题,请使用其他变量,例如您的代码应如下所示:

  for (int i = 0; i < howMany; i++) {//loop 1
    ...
    for (int k = 1; k <= returnMe.length; k++) {//loop 2
    //-------^------^---------------------^

并且程序将生成您想要的内容。