使用Java中的冒泡排序进行数组排序时出错

时间:2011-12-10 04:24:36

标签: java sorting bubble-sort

我正在尝试创建一个数组,其中包含最小和最大之间的“总”数字。然后,使用冒泡排序对它们进行排序。当我执行时,我得到全零。有人能找到出错的地方吗?我们将非常感谢您的回复。

import java.util.*;
import java.util.Random;

public class final_project 
{ 
    public static void main(String[] args) 
    { 
        int numbers[]; 
        int i, min, max, total; 
        int num;
        Scanner scan = new Scanner(System.in);

        System.out.println("Please enter a minimum random value");
        min = scan.nextInt();
        System.out.println("Please enter a maximum random value");
        max = scan.nextInt();
        System.out.println("Please enter the amount of random numbers");
        total = scan.nextInt();

        numbers = new int[total];


        i = 0;
        total = 0;
        while ( i < total )
        {
            num = min + (int)(Math.random()*max);;
            numbers[i] = num;  
            total += num; 

            i += 1; /* i = i + 1; */
        }


        bubbleSort(numbers, numbers.length); 
        System.out.println("Your Sorted Array Is: "); 
        for(i=0; i<numbers.length; i++) 
        { 
            System.out.print(numbers[i] + " "); 
        } 

    }



    private static void bubbleSort(int[] numbers, int length) 
    { 
        int temp, counter, index; 

        for(counter=0; counter<length-1; counter++) 
        { 
            for(index=0; index<length-1-counter; index++) 
            { 
                if(numbers[index] > numbers[index+1]) 
                { 
                    temp = numbers[index]; 
                    numbers[index] = numbers[index+1]; 
                    numbers[index+1] = temp; 
                } 
            } 
        } 
    } 
}

3 个答案:

答案 0 :(得分:0)

你的循环没有执行:

        i = 0;
        total = 0;
        while ( i < total )
            ...

此外,您不想增加total。用以下代码替换你的循环:

        for(int i = 0; i < numbers.length; ++i)
        {
             numbers[i] = num;  
        }

答案 1 :(得分:0)

您应该考虑使用for循环而不是while循环。 for循环非常适合迭代数组。

答案 2 :(得分:0)

更改

while ( i < total )

while ( i < numbers.length )