Abdirahman Hashi
Abdirahman Hashi

Reputation: 71

Array sort leaves one element in the wrong position

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

Upvotes: 5

Views: 408

Answers (3)

TaQuangTu
TaQuangTu

Reputation: 2343

You must modify a bit at the loop.

for(int i = 0; i < numbers.length-1; i++){  //modify at this line
    for(int j = i+1; j < numbers.length; j++){  //also modify at this line
        if(numbers[i] > numbers[j]){  //modify to get ascending oder
              holder = numbers[i];
              numbers[i] = numbers[j];
              numbers[j] = holder;
        }
    }
}

Upvotes: 2

Jacob G.
Jacob G.

Reputation: 29700

It looks as though one possible, inefficient solution would be to change:

for (int j = 1; j < numbers.length; j++) {

To the following:

for (int j = 0; j < numbers.length; j++) {

This inadvertently double-swaps every value in the array, but works!

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 361685

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])

Upvotes: 2

Related Questions