Java 中使用 BubbleSort 进行数组排序时出错
我正在尝试创建一个数组,其“总”数量在最小值和最大值之间。然后,使用冒泡排序对它们进行排序。当我执行时,我得到全零。有人能发现出了什么问题吗?若能及时回复,我们将不胜感激。
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;
}
}
}
}
}
I am trying to create an array with 'total' amount of numbers between min and max. And then, sort them using bubble sort. When i execute, i get all zeros. Could someone find what is going wrong? A prompt reply would be appreciated.
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;
}
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更改
为
Change
to
您的循环不执行:
您也不想增加
total
。将循环替换为:Your loop doesn't execute:
Also you don't want to increment
total
. Replace your loop with:您应该考虑使用 for 循环而不是 while 循环。 for 循环非常适合迭代数组。
You should consider using a for loop instead of a while loop. A for loop is perfect for iterating through an array.