随机数数组排序 [英] Random number array sorting

查看:83
本文介绍了随机数数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在对随机数数组进行排序时遇到问题。

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;
}

这篇关于随机数数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆