Enter 10 characters: q w e r t y u i o p
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 . . .
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();
}
}
clone().First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.