简体   繁体   中英

Why isnt my bubble sort method working?

I want to try to figure it out, I just kind of need to be pointed in the right direction. Please don't just write the solution, I would like to understand what I need to do to make it work.

    static void bubbleSort() {
        int [] a = {1,3,4,2,5};
        int [] b = new int[a.length];
        int j = 0;

        for(int c = 0;c <= a.length;c++){//this loop doesnt even do anything??? 
            for(int i = 0;i<a.length-j;i++){

                if(a[i]>a[i+1]){
                    b[i] = a[i+1];
                    b[i+1] = a[i];
                    j++;
                }
                else{
                    b[i] = a[i];
                    b[i+1] = a[i+1];
                    j++;
                }
            }
        }

        for(int i = 0; i< b.length ; i++)
            System.out.println(b[i]);
    }

There are many issues with your code -

1) You don't need an extra array 'b', bubble sort can be done inplace.

2) Think the use of 'j', replace it with 'c' and check how this makes the difference in the looping.

3) Your new sorted array is coming up in 'b' and still at every step you are checking the condition -

if(a[i]>a[i+1])

Don't you think, 'b' has a role to play here?

Consider the above points and comment on this post if you still have issues.

Not absolutely sure, but i think this should be the corrected implementation

static void bubbleSort() {
    int [] a = {1,3,4,2,5};
    for(int c = 0;c < a.length;c++){//now it does 
        for(int i = 0;i+1<a.length-c;i++){

            if(a[i]>a[i+1]){
                int tmp = a[i];
                a[i] = a[i+1];
                a[i+1] = tmp;
            }
        }
    }

    for(int i = 0; i< a.length ; i++)
        System.out.println(a[i]);
}

You run over a again and again, but you changed b, which you didnt compare. So your first for loop was doing nothing. You dont need j, c works. Because if you made 1 cycle in the inner loop, the biggest number is at the end, so you dont have to check it again. The c-loop should run till c

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