Warm tip: This article is reproduced from stackoverflow.com, please click
arrays int java numbers sorting

Sorting list of numbers

发布于 2020-03-27 10:21:42

I am trying to sort a list of numbers from smallest to the biggest and print it. I've tried two things:

1.

public class Sorter {
    public static void main(String[] args) {
        int[] numbers = {1, 3, 8, 2, 5, -2, 0, 7, 15};
        int[] sorted = new int[numbers.length];

        for (int a = 0; a < numbers.length; a++) {
            int check = 0;
            for (int b = 0; b < numbers.length; b++) {
                if (numbers[a] < numbers[b]) {
                    check++;
                }
            }
            sorted[check] = numbers[a];
        }

        for (int c = numbers.length - 1; c >= 0; c--) {
            System.out.print(sorted[c] + ", ");
        }
    }
}

and this thing works, but won't work with repeated values, so I tried this other thing

public class Sortertwo {
    public static void main(String[] args) {
        int[] numinput = {3, 2, 1, 4, 7, 3, 17, 5, 2, 2, -2, -4};
        int[] numsorted = new int[numinput.length];

        int n = 0;
        for (; n < numinput.length; ) {

            for (int b = 0; b < numinput.length; b++) {
                int check = 0;
                for (int c = 0; c < numinput.length; c++) {
                    if (numinput[b] <= numinput[c]) {
                        check++;
                    }
                }

                if (check >= (numinput.length - n) && numinput[b] != 0) {
                    numsorted[n] = numinput[b];
                    numinput[b] = 0;
                    n++;
                }

                if (n >= (numinput.length)) {
                    break;
                }
            }
        }

        for (int g = 0; g < numinput.length; g++) {
            System.out.print(numsorted[g] + ", ");
        }
    }
}

Where it relies on the thing that once the number from the first array is used (the smallest one is found), it has to be ignored when the program goes through the array next time around. I tried to assign it like null value, but it doesn't work, so I assigned it to zero and then ignore it, which is a problem, because the list cant have a zero in it. Is there any like better way to go about it? Thanks.

Questioner
Runciter
Viewed
65
Playturbo 2019-07-03 22:22

You can always use:

Arrays.sort(numbers);