0

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

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

preincrement is also wrong, because then he will skip a few checks. So instead of i++ he should use i+1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.