随机数数组排序
问题描述:
我在对随机数数组进行排序时遇到问题。
I'm having an issue sorting my random number array.
我想做的是一个if语句,以确保 arr [0]
总是更大小于 arr [1]
。
What I'd like to do is make an if statement to make sure arr[0]
is always greater than arr[1]
.
为什么?好吧,我的程序会生成两个0到99之间的随机数,并且会执行一些简单的数学问题,例如减法和除法。由于您无法正确划分55/99,因此第一个 arr [0]
应该始终大于 arr [1]
。
Why? Well, my program generates two random numbers from 0 - 99, and it does simple math problems such as subtraction and division. Since you can't divide 55 / 99 properly, the first arr[0]
should always be larger than arr[1]
.
在这里,谢谢您的帮助!
Here's where I'm at and thanks for your help!
public static int[] randomNumbers(){
Random obj = new Random();
int arr[] = new int[2]; //init array to hold 2 numbers
arr[0] = obj.nextInt(99); //number 1 randomized 0 - 9 // sort array
arr[1] = obj.nextInt(99); //number 2 randomized 0 - 9
//do compare to make sure arr[0] is always greater than arr[1]
//but how???
return arr;
/*int rgen = obj.nextInt(10); //first number has to be larger than second 0 - 10
int rgen1 = obj.nextInt(9); //random 0 - 9
int randomNumber = rgen + rgen1; //stores the answer*/
}
答
只需生成两个数字,然后在第二个数字较大时进行切换。
Just generate two numbers, and then switch them if the second is larger.
if (arr[1] > arr[0]) {
int temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
}