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.
Topic: Bubble sort on a character array
Answer
import java.util.Scanner;
class BubbleChar { public static void main(String args[]) { Scanner sc = new Scanner(System.in); char ch[] = new char[10]; char orig[] = new char[10]; char temp;
System.out.println("Enter 10 characters :"); for(int i = 0; i < 10; i++) { ch[i] = sc.next().charAt(0); orig[i] = ch[i]; }
for(int i = 0; i < 9; i++) { for(int j = 0; j < 9 - i; j++) { if(ch[j] > ch[j + 1]) { temp = ch[j]; ch[j] = ch[j + 1]; ch[j + 1] = temp; } } }
System.out.print("Original array : "); for(int i = 0; i < 10; i++) System.out.print(orig[i] + " "); System.out.println();
System.out.print("Sorted array : "); for(int i = 0; i < 10; i++) System.out.print(ch[i] + " "); } }
Bubble sort is a certainty in this paper. Learn the shape exactly.
The method compares ADJACENT pairs and swaps them if they are out of order, so after each pass the largest remaining value has bubbled to the end. outer loop: i from 0 to n-2, one pass per element inner loop: j from 0 to n-2-i, because the last i elements are already in place the comparison is between ch[j] and ch[j+1] — adjacent, which is what distinguishes bubble from selection sort
The swap needs a temporary variable: temp = a; a = b; b = temp. Writing a = b; b = a; destroys the first value.
The extra requirement here is displaying the ORIGINAL array as well. Since sorting overwrites ch[], a second array orig[] takes a copy at input time. Note you cannot simply write orig = ch — that would make both names refer to the same array, and the "original" would come out sorted too. Copy element by element.
Characters compare correctly with > because Java uses their Unicode values, so no special handling is needed.
ch[] char[10] - the characters entered, sorted in place orig[] char[10] - a copy of the characters as originally entered temp char - temporary variable used during the swap i, j int - loop variables for the passes and comparisons sc Scanner - object used to read input