roshan sawant
roshan sawant

Reputation: 1

why does this bubblesort not working by using simple static integer array?

I have been trying to implement Bubble Sort using simple static integer array in java. However there seems to be some problem.

class BubbleSort {
    static int[] a = { 10, 8, 11, -6, 9 };

    public void swap(int i, int k) {
        if (a[i] == a[k])
            return;

        int temp;
        temp = a[i];
        a[i] = a[k];
        a[k] = temp;

    }

    public static void main(String[] args) {
        BubbleSort bs = new BubbleSort();
        for (int end = a.length - 1; end > 0; end--) {
            for (int i = 0; i < end; i++) {
                if (a[i] > a[i + 1])
                    bs.swap(i, i++);
            }
        }
        for (int j = 0; j < a.length; j++)
            System.out.println(a[j]);

    }
}

i expect output -6,8,9,10 but the actual output is not sorted at all.it is showing 10,8,-6,9

Upvotes: 0

Views: 71

Answers (2)

CaptainDaVinci
CaptainDaVinci

Reputation: 1065

The issue lies in the following statement:

bs.swap(i, i++);

Because of the postincrement, bs.swap will be called with the same values of i as post increment returns the previous value. Instead, you should call bs.swap(i, i + 1).

Upvotes: 2

Konrad Neitzel
Konrad Neitzel

Reputation: 760

Your mistake is inside the call of swap. Your code

bs.swap(i, i++);

is the same as:

bs.swap(i, i); i=i+1;

But you do not want to increase i and of course: You want to call it with i and i+1. So change it to

bs.swap(i, i+1);

Upvotes: 4

Related Questions