Search code examples
javasortingbubble-sort

bubble sort with a boolean to determine whether array is already sorted


I have following code for bubble sort but its not sorting at all. if I remove my boolean then its working fine. I understand that since my a[0] is lesser than all other elements therefore no swapping is being performed can anybody help me with this.

package com.sample;

public class BubleSort {
    public static void main(String[] args) {
        int a[] = { 1, 2, 4, 5, 6, 88, 4, 2, 4, 5, 8 };
        a = sortBuble(a);
        for (int i : a) {
            System.out.println(i);
        }

    }

    private static int[] sortBuble(int[] a) {
        boolean swapped = true;
        for (int i = 0; i < a.length && swapped; i++) {
            swapped = false;
            System.out.println("number of iteration" + i);

            for (int j = i+1; j < a.length; j++) {

                if (a[i] > a[j]) {
                    int temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                    swapped = true;
                }
            }
        }

        return a;
    }
}

Solution

  • Your bubble sort is wrong?

        private static int[] sortBuble(int[] a) {
            boolean swapped = true;
            int n = a.length;
            for (int i = 0; i < n && swapped; i++) {
                swapped = false;
                int newn = 0;
                System.out.println("number of iteration" + i);
    
                for (int j = 1; j < a.length; j++) {
    
                    if (a[j-1] > a[j]) {
                        int temp = a[j-1];
                        a[j-1] = a[j];
                        a[j] = temp;
                        swapped = true;
                        newn = j;
                    }
                }
                n = newn;
            }
    
            return a;
        }