gigs
gigs

Reputation: 1531

Java. Help figure out why my code doesn't work

here is my code, i can't figure out why it doesn't work. This algorithm have to sort array but when i run it, it retreive me the same array.

import java.util.Arrays;

public class BubbleSorted1 {

    public static void main(String[] args) {
        int[] data = {40,20,50,30,10};
        sort(data);
        System.out.println(Arrays.toString(data));

    }

    public static void sort(int[] array){
        for(int barrier = array.length-1; barrier >= 0; barrier--){
            for(int index = 0; index < barrier; index++){
                if(array[index] > array[index] + 1){
                    int tmp = array[index];
                    array[index] = array[index + 1];
                    array[index + 1] = tmp;
                }
            }
        }

    }

}

Upvotes: 0

Views: 79

Answers (3)

Michael
Michael

Reputation: 222

You write array[index] > array[index] + 1. This should probably have been array[index] > array[index + 1] as the check you do is always false.

Upvotes: 3

Narmer
Narmer

Reputation: 1454

You have a typo here:

if(array[index] > array[index] + 1){

I think you meant:

if(array[index] > array[index + 1]){

The first condition can never be true because a number (the value contained in the index of the array) won't never be greater than itself plus one.

Upvotes: 2

SonalPM
SonalPM

Reputation: 1337

Try this.. Only thing You need to change is IF condition

 public static void sort(int[] array){
                for(int barrier = array.length-1; barrier >= 0; barrier--){
                    for(int index = 0; index < barrier; index++){
                        if(array[index] > array[index+1]){
                            int tmp = array[index];
                            array[index] = array[index + 1];
                            array[index + 1] = tmp;
                        }
                    }
                }

Upvotes: 0

Related Questions