开发者

Array sort by Ascending in for loop

开发者 https://www.devze.com 2023-03-21 14:36 出处:网络
I got trouble wh开发者_StackOverflow中文版en i try to sort array in for loop. I give you my code follow:

I got trouble wh开发者_StackOverflow中文版en i try to sort array in for loop.

I give you my code follow:

public class Lottery {

    public Lottery() {
        java.util.Random iRandom = new java.util.Random();
        int num[] = new int[6];
        java.util.Arrays.sort(num);

        for(int i =0 ; i < num.length; i++) {
            java.util.Arrays.sort(num);
            num[i] = iRandom.nextInt(49)+1;
            System.out.println(num[i]);
        }
    }

    public static void main(String[] args) {
        Lottery lott = new Lottery();
    }
}

In my above code, i can print random number for using "For Loop" but i try to sort it by ascending but it doesnt work.....

The way i do is right?

Could everybody can help me?

Thank you!

Best Regards!


Put the Arrays.sort(num) call AFTER you're finished generating the random numbers.

public Lottery(){
    java.util.Random iRandom = new java.util.Random();
    int num[] = new int[6];

    for(int i =0 ; i < num.length; i++)
        num[i] = iRandom.nextInt(49)+1;

    Arrays.sort(num);
}


You're sorting the array as you go through it and inserting data into the array.

What you should be doing is:

public Lottery() {
    java.util.Random iRandom = new java.util.Random();
    int num[] = new int[6];
    //java.util.Arrays.sort(num);

    for(int i =0 ; i < num.length; i++) {
        num[i] = iRandom.nextInt(49)+1;
    }

    java.util.Arrays.sort(num);

    for(int i : num) {
        System.out.println(i);
    }
}


You're changing the array after you sort it, which breaks the sort order.


What you can do to sort in acceding order is:

 java.util.Arrays.sort(array);

edit: Also as said in the comments: Get the random numbers you want. Then sort in revese. (to much sorting can make the program slow)

0

精彩评论

暂无评论...
验证码 换一张
取 消