Home / Programs / 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.
Programming Example

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.

👁 136 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

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 Code

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();
    }
}

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.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.