嘿,有Stack Overflow社区,所以我还是Java的新手,但我正在努力学习如何排序。现在我的程序从1到10的范围内创建n个随机数。虽然如何将这些数字放入要排序的数组中,但我不太确定。我应该去做一个冒泡排序而不是Arrays.sort吗?
这是我的代码
public static final void main(String aArgs){
//User inputs a number for the amount of random numbers to generate
String UserNumbers = JOptionPane.showInputDialog("How many numbers would you like to generate?");
//The unknown amount of numbers "n" is converted from the "UserNumbers" String to an int
int n = Integer.parseInt(UserNumbers);
//Random number generator generating the amount of numbers as defined by the user
Random randomGenerator = new Random();
for (int idx = 1; idx <= n; ++idx){
int randomInts = randomGenerator.nextInt(10);
//Now to create an array for the random numbers to be put into so they can be sorted
int ArrayToSort[] = new int[n];
ArrayToSort[0] = randomInts;
Arrays.sort(ArrayToSort);
System.out.println(ArrayToSort);
}
}
}
答案 0 :(得分:3)
我怀疑你不是在问是否使用冒泡排序,因为它比Arrays.sort更快/更慢,而是作为Arrays.sort不适合你。
我认为这是因为您没有将您生成的随机数放入您排序的数组
相反,请尝试以下代码:
public static final void main(String args){
//User inputs a number for the amount of random numbers to generate
String userNumbers = JOptionPane.showInputDialog("How many numbers would you like to generate?");
//The unknown amount of numbers "n" is converted from the "userNumbers" String to an int
int n = Integer.parseInt(userNumbers);
//Random number generator generating the amount of numbers as defined by the user
int arrayToSort[] = new int[n];
Random randomGenerator = new Random();
for (int idx = 0; idx < n; ++idx){
arrayToSort[idx] = randomGenerator.nextInt(10);
}
Arrays.sort(arrayToSort);
System.out.println(arrayToSort);
}
您的代码的问题在于您尝试使用随机数填充大小为n的数组,对其进行排序然后打印,但您的代码在每次迭代中生成一个随机数,分配一个n大小的数组,put&# 39; s数组的第0个插槽中的随机数并对其进行排序,并将其打印出来(这样做n次) - 它不会获得相同的效果
BTW,Random.nextInt(10)返回一个介于0和9之间的随机数,而不是1和10.来实现你想要的,你需要为该随机值加1答案 1 :(得分:0)
Arrays.java的sort方法使用quicksort表示基元数组,并对对象数组进行合并排序。我相信大部分时间快速排序比合并排序更快,并且内存更少。
来源: Why does Java's Arrays.sort method use two different sorting algorithms for different types?