Define a class to accept 10 characters from a user. Using bubble sort technique arrange them in ascending order. Display the sorted array and original array.

Java Programming Language (Article) (Program)

127

Given Input:

Enter 10 characters:
q w e r t y u i o p

Expected Output:

Enter 10 characters:
q w e r t y u i o p

Original Array:
q w e r t y u i o p
Sorted Array:
e i o p q r t u w y Press any key to continue . . .

Program:

import java.util.Scanner;

public class BubbleSortCharacters {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        char[] arr = new char[10];

        // Accept 10 characters from the user
        System.out.println("Enter 10 characters:");
        for (int i = 0; i < 10; i++) {
            arr[i] = scanner.next().charAt(0);
        }

        // Store the original array for display
        char[] originalArr = arr.clone();

        // Bubble Sort Algorithm
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    // Swap elements
                    char temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }

        // Display Original and Sorted Arrays
        System.out.println("\nOriginal Array:");
        for (char ch : originalArr) {
            System.out.print(ch + " ");
        }

        System.out.println("\nSorted Array:");
        for (char ch : arr) {
            System.out.print(ch + " ");
        }

        scanner.close();
    }
}

Output:


                                        

Explanation:

How It Works

  1. The program accepts 10 characters from the user.
  2. It stores the original array using clone().
  3. The Bubble Sort algorithm sorts the characters in ascending order.
  4. The program displays both the original and sorted arrays.

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.