java - 尝试使用冒泡排序对随机整数数组从最大到最小进行排序

标签 java arrays sorting

因此,作为任务的一部分,我被要求创建一个具有一定范围内的随机值的数组,然后将其从小到大排序(我使用了冒泡排序),然后首先打印数组中的所有元素,然后从小到大列出它们。

我的问题是我不断收到 ArrayIndexOutOfBoundsException 错误,但找不到问题所在。

您可以在我放入 randomArrays 方法的代码中看到,一个 for 循环为我在 main 方法中声明的数组大小创建随机值,然后,在 for 循环下面,我创建了一个if 语句检查一个元素的值是否大于其后面的元素,如果是,则交换元素的位置,直到将它们全部排序为最小到最大,然后终止循环。

非常感谢您的帮助,谢谢:)

public class MyArray {

public static void main(String[] args) {
    int[] elements = new int[50];
    int min = 0;
    int max = 50;

    randomArrays(elements, max, min);

}

public static void randomArrays(int[] elements, int max, int min) {
    int range = max - min; //defines the range of the integers
    int temp;
    boolean fixed = false;

    while (fixed == false) {
        fixed = true;

        for (int i = 0; i < elements.length; i++) {
            elements[i] = min + (int) (Math.random() * range);
            while (i < elements.length) {
                if (elements[i] > elements[i + 1]) {
                    //if 8   >    5
                    temp = elements[i + 1];
                    //store 5 in temp
                    elements[i + 1] = elements[i];
                    //put the 8 in the 5's place
                    elements[i] = temp;
                    fixed = false;
                }
                i++;
            }

        }
    }

}
//System.out.println(elements[i]);
}

最佳答案

My issue is that I keep getting the ArrayIndexOutOfBoundsException error, but cannot find where this problem lies.

问题出在for循环的条件上。当 i=49 时,您会收到 ArrayOutOfBounds 异常,然后尝试访问不存在的 i+1 索引。

改变

for (int i = 0; i < elements.length; i++)

for (int i = 0; i < elements.length-1; i++)

关于java - 尝试使用冒泡排序对随机整数数组从最大到最小进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48172110/

相关文章:

c++ - 对指针 vector 进行排序工作一次然后崩溃 "unable to read memory"

java - 从外部中间件获取 RecordStore 数据

java - 如何在java中将元素推送到空的固定大小数组

php - 内爆和爆炸多维数组

javascript - 为什么保存的数组的值会改变?

php - 按范围 10 x 10 对数组进行排序

algorithm - 在快速排序中使用一次插入排序

java - 正则表达式获取逗号分隔值中的第 n 个值

java - Maven 构建错误

java - java中循环迭代时如何计算特定字符串是否匹配?