Runciter
Runciter

Reputation: 23

Sorting list of numbers

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.

Upvotes: 2

Views: 115

Answers (3)

OscarRyz
OscarRyz

Reputation: 199215

Unless this is homework, using Arrays.sort as the comments suggest, should be the way to go

import java.util.Arrays;

public class S {
    public static void main(String ... args) {
        int[] numbers = {1, 3, 8, 2, 5, -2, 0, 7, 15};
        Arrays.sort(numbers);
        System.out.println(Arrays.toString(numbers));
    }
}

Prints:

[-2, 0, 1, 2, 3, 5, 7, 8, 15]

Upvotes: 0

ph7
ph7

Reputation: 169

If you want to use your first method then change this:

if (numbers[a] < numbers[b])
{
    check++;
}

to:

if (numbers[a] <= numbers[b]) 
{
    check++;
}

Upvotes: 0

Playturbo
Playturbo

Reputation: 91

You can always use:

Arrays.sort(numbers);

Upvotes: 3

Related Questions