I am trying to sort an array in ascending order and I came across a problem. The code sorts the array but it takes the last number and places it in the first position of the array. So for example when ordering 2,3,4,1 the output is 4, 1, 2, 3. How do I take the number 4 and move it behind the number 3?
public class Main {
public static void main(String[] args) {
int[] numbers = {2, 3, 1, 4};
int holder = 0;
for(int i = 0; i < numbers.length; i++){
for(int j = 1; j < numbers.length; j++){
if(numbers[i] < numbers[j]){
holder = numbers[i];
numbers[i] = numbers[j];
numbers[j] = holder;
}
}
}
// prints array
for(int i = 0; i < numbers.length; i++){
System.out.println(numbers[i]);
}
}
}
Output:
4
1
2
3
There are two major problems.
One is that you're swapping some elements twice. You want to always make sure that i
is less than j
so that numbers[i]
is to the left of numbers[j]
. The way your loops work, in later iterations j
starts out lower than i
. For instance, when i
is 2 the inner loops starts with j
at 1. To fix this you can always start j
at 1 place higher than i
:
for(int j = i + 1; j < numbers.length; j++) {
If you fix that you'll notice the second problem: the array is sorted in reverse! That's because the <
comparison is backwards. You want to swap items when the left one is larger than the right one, not when it's smaller. If it's smaller they're already in the correct order.
if(numbers[i] > numbers[j])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With