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);
}
可能的重复[Java:创建与随机int的数组(int只能使用一次)](http://stackoverflow.com/questions/7940439/java-create-array-with-random-ints-ints-只能使用一次) –
*我想让用户判断有多少数字随机生成到数组中*:然后开始询问用户他想要多少个数字,然后只创建一个数字适当大小的数组:用户输入的大小。 –
@JBNizet这是我的脑力激荡的一部分,我不知道如何写出数组,而不是固定的数量,它需要用户输入。我得到了铸造和输入错误。 – Jcrow