冒泡排序没有正确排序

时间:2015-03-28 02:03:08

标签: java sorting bubble-sort

所以,在我的程序中,我正在尝试使用随机数填充数组并使用冒泡排序对它们进行排序。当我运行我的程序时,我可以在排序开始之前清楚地看到随机生成的数字,但是在我运行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;
            }

        }
    }

}
}

3 个答案:

答案 0 :(得分:0)

您不需要请求2个输入,必须使用相同的输入来调整阵列的大小并填充它。

在你当前的例子中,如果我输入2个不同的值,比如说10然后是5,那么我最终会在数组中输出5个零(0是默认的int值)。

您的排序算法看起来很好。

答案 1 :(得分:0)

你的num_i实际上是数组的大小 它不是迭代次数。

int array[] = new int[n];

int array[] = new int[num_i];

使用和n和num_i不写。您应该使用随机数完全填充数组。

答案 2 :(得分:0)

这不是必需的:

 System.out.println("How many times should the loop be iterated? ");

实际上,num_i是多余的。一旦你指定有&#39; n&#39;元素,让随机数生成器填充&#39; n&#39;随机值。

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