Bubble Sort In Java

import java.util.*;
public class bs {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(“Start”);
int size = sc.nextInt();
int array [] = new int[size];
for(int i =0;i<array.length;i++){
array[i]=sc.nextInt();
}
System.out.println(“Initial Array:”);
printArray(array);
clbs(array);
}

public static void clbs(int[] arr) {

    int n = arr.length;
    boolean swapped;
    int swapCount = 0;

    for (int i = 0; i < n - 1; i++) {
        swapped = false;

        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {

                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = true;
                swapCount++;

                System.out.println("Swapped " + arr[j] + " and " + arr[j + 1]);
                printArray(arr);
            }
        }


        if (!swapped) {
            break;
        }
    }

    System.out.println("Total number of swaps: " + swapCount);
}

public static void printArray(int[] arr) {
    for (int num : arr) {
        System.out.print(num + " ");
    }
    System.out.println();
}

}

Leave a Reply

Your email address will not be published. Required fields are marked *