Write a JAVA program to sort for an element in a given list of elements using bubble sort.

 import java.util.Scanner;


public class BubbleSortExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);


        // Taking input

        System.out.print("Enter number of elements: ");

        int n = scanner.nextInt();


        int[] arr = new int[n];

        System.out.println("Enter " + n + " elements:");

        for (int i = 0; i < n; i++) {

            arr[i] = scanner.nextInt();

        }


        // Bubble Sort Logic

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

            boolean swapped = false;

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

                if (arr[j] > arr[j + 1]) {

                    // Swap arr[j] and arr[j+1]

                    int temp = arr[j];

                    arr[j] = arr[j + 1];

                    arr[j + 1] = temp;

                    swapped = true;

                }

            }

            // If no two elements were swapped in inner loop, break

            if (!swapped) {

                break;

            }

        }


        // Display sorted array

        System.out.println("Sorted array:");

        for (int i = 0; i < n; i++) {

            System.out.print(arr[i] + " ");

        }


        scanner.close();

    }

}

Output:


Comments