#Sort without .sort

1 messages · Page 1 of 1 (latest)

fair moth
#
import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void sort(int[] numbers) {
        int tempVar;
        for (int j = 0; j < numbers.length; j++) {
            for (int i = 1; i < numbers.length; i++) {
                if (numbers[i] > numbers[j]) {
                    tempVar = numbers[j];
                    numbers[j] = numbers[i];
                    numbers[i] = tempVar;
                }
            }
        }
    }

    /* Do not change code below */
    public static void main(String[] args) {
        final Scanner scanner = new Scanner(System.in);
        String[] values = scanner.nextLine().split("\\s+");
        int[] numbers = Arrays.stream(values)
                .mapToInt(Integer::parseInt)
                .toArray();
        sort(numbers);
        Arrays.stream(numbers).forEach(e -> System.out.print(e + " "));
    }
}```
why doesnt this code sort the items, when I read it, it seems like it would work but it doesnt
tranquil cliffBOT
#

This post has been reserved for your question.

Hey @fair moth! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

dark violet
#

I guess you are trying to do bubble sort?

fair moth
#

for example, if I put
3 1 2
i want it to give me the output
1 2 3

#

5 4 3 1 2
1 2 3 4 5

dark violet
#

yeah man I know what a sorting algorithm is kekw

#

there are just different ways to achieve it

fair moth
#

sorry im new to java

#

and programming

dark violet
#

bubble sort is the simplest and usually taught first

#

I think it's explained pretty well and you can see the code afterwards

fair moth
#

thakn you

dark violet
#

also a tip
I see you've swapped i and j in the loops. (typically you'd do i - outer, j - inner) I also did similar things early on cuz I thought that way I was showing that I know what I'm doing. It's a bad idea cuz of semantics (readability).