简体   繁体   中英

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;
                }
            }
        }

    }

}

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.

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.

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;
                        }
                    }
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM