【发布时间】:2015-10-26 20:42:37
【问题描述】:
package selectionsortintro;
public class SelectionSortIntro {
public static void main(String[] args) {
int nums[] = { 22, 30, 15, 1, 7, 87, 65, 24, 22, 0 };
// print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
System.out.println("\n---------------------------------");
selectionSort(nums);
// print out sorted list
System.out.println("After sorting using the Selection Sort," + " the array is:");
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
}
public static void selectionSort(int data[]) {
int smallest;
for (int i = 0; i < data.length - 1; i++) {
smallest = i;
// see if there is a smaller number further in the array
for (int index = i + 1; index < data.length; index++) {
if (data[index] < data[smallest]) {
swap(data, smallest, index);
}
}
}
}
public static void swap(int array2[], int first, int second) {
int hold = array2[first];
array2[first] = array2[second];
array2[second] = hold;
}
}
我想将随机数量的随机整数添加到数组中,因此选择排序算法会将它们排序出来。唯一的问题是,我不知道如何用随机数存储数组而不是固定数量。如果这令人困惑,那么当你制作数组时就像:
int[] randomNumbers = new int[20];
其中 20 是生成的数字数量。好吧,我想让用户判断有多少数字随机生成到数组中。所以我在想也许使用 ArrayList?但是,我对如何使用它将随机数添加到自身感到困惑。如果有人可以帮助我,那就太棒了
编辑:所以我使用扫描仪获得输入,但我真的更喜欢 JOptionPane,因为输入对话框看起来更好,但如果扫描仪是唯一的方法,那很好。所以现在已经完成了,我只需要用随机整数实际填充数组,有人知道怎么做吗?
这就是我想出的,我的代码出错了,如果有人能提供帮助,那就太棒了。
Scanner input = new Scanner(System.in);
Scanner s = new Scanner(System.in);
System.out.println("enter number of elements");
int n = s.nextInt();
int nums[]=new int[n];
Random randomGenerator = new Random();
//print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
nums[n] = randomGenerator.nextInt(1001);
}
【问题讨论】:
-
我想让用户判断随机生成多少个数字到数组中:然后首先询问用户他想要多少个数字,然后只创建一个适当大小的数组:用户输入的大小。
-
@JBNizet 这就是我的部分大脑,我不知道如何写出数组,所以它不是固定数量,而是需要用户输入。我收到投射和类型错误。