Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 冒泡排序不是';t正确分类_Java_Sorting_Bubble Sort - Fatal编程技术网

Java 冒泡排序不是';t正确分类

Java 冒泡排序不是';t正确分类,java,sorting,bubble-sort,Java,Sorting,Bubble Sort,所以,在我的程序中,我试图获取一个充满随机数的数组,并使用冒泡排序对它们进行排序。当我运行我的程序时,我可以在排序开始之前清楚地看到随机生成的数字,但是在我运行bubbleSort方法之后,这些数字都是0 我肯定我忽略了一些小事,但这让我发疯了!如有任何建议,将不胜感激。提前谢谢你 import java.util.Random; import java.util.Scanner; public class partThree { public static void main(Strin

所以,在我的程序中,我试图获取一个充满随机数的数组,并使用冒泡排序对它们进行排序。当我运行我的程序时,我可以在排序开始之前清楚地看到随机生成的数字,但是在我运行bubbleSort方法之后,这些数字都是0

我肯定我忽略了一些小事,但这让我发疯了!如有任何建议,将不胜感激。提前谢谢你

import java.util.Random;
import java.util.Scanner;


public class partThree {

public static void main(String[] args) {

    Scanner scan = new Scanner (System.in);
    Random rand = new Random();

    int max = 1000;

    System.out.println("How many items are in the array? ");
    int n = scan.nextInt();
    int array[] = new int[n];

    System.out.println("How many times should the loop be iterated? ");
    int num_i = scan.nextInt();

    rand.nextInt(max);

    for(int i=0; i<num_i; i++)
        array[i] = rand.nextInt(max);

    System.out.println("Before sorting: ");
    for(int i=0; i<num_i; i++){
        System.out.println(array[i]);
    }

    bubbleSort(array);
    System.out.println();

    System.out.println("After sorting: ");
    for(int i=0; i<num_i; i++){
        System.out.println(array[i]);
    }

}

public static void bubbleSort(int[] array){

    int n = array.length;
    int temp = 0;

    for(int i=0; i < n; i++){
        for(int j=1; j < (n-i); j++){

            if(array[j-1] > array[j]){
                temp = array[j-1];
                array[j-1] = array[j];
                array[j] = temp;
            }

        }
    }

}
}
import java.util.Random;
导入java.util.Scanner;
公共课第三部分{
公共静态void main(字符串[]args){
扫描仪扫描=新扫描仪(System.in);
Random rand=新的Random();
int max=1000;
System.out.println(“数组中有多少项?”);
int n=scan.nextInt();
int数组[]=新的int[n];
println(“循环应该迭代多少次?”);
int num_i=scan.nextInt();
耐克斯汀兰特(最高);

对于(int i=0;i您不需要请求2个输入,必须使用相同的输入来调整数组大小并填充它

在您当前的示例中,如果我输入2个不同的值,比如10,然后是5,那么数组中会有5个零(0是默认的int值)


您的排序算法看起来不错。

您的num\u i实际上就是数组的大小。
这不是迭代次数

int array[] = new int[n];

同时使用and n和num_i不是写操作。您应该使用随机数完全填充数组。

这不是必需的:

 System.out.println("How many times should the loop be iterated? ");
事实上,num_i是多余的。一旦指定有'n'个元素,让随机数生成器填充'n'个随机值

for(int i=0; i<n; i++)
        array[i] = rand.nextInt(max);

for(int i=0;ii如果您认为下面的任何答案是正确的,请将其标记为答案或向上投票。
for(int i=0; i<n; i++)
        array[i] = rand.nextInt(max);