Write a program to input 15 integer elements in an array and sort them in ascending order using the bubble sort technique.
Topic: Bubble sort on an integer array
Answer
import java.util.Scanner;
class BubbleSort { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int a[] = new int[15]; int temp;
System.out.println("Enter 15 integers :"); for(int i = 0; i < 15; i++) a[i] = sc.nextInt();
for(int i = 0; i < 14; i++) { for(int j = 0; j < 14 - i; j++) { if(a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } }
System.out.println("Sorted array in ascending order :"); for(int i = 0; i < 15; i++) System.out.print(a[i] + " "); } }
The bubble sort template, worth learning exactly since it appears almost every year.
The method compares ADJACENT elements and swaps them when they are out of order. After each complete pass the largest remaining value has bubbled to the end, which is why the inner loop can stop one place earlier each time. outer loop: i from 0 to n-2 inner loop: j from 0 to n-2-i compare a[j] with a[j+1]
For ascending order the test is a[j] > a[j+1]; reverse it to < for descending. That single character is the only change needed.
The swap needs a temporary variable — temp = a; a = b; b = temp. Writing a = b; b = a; loses the first value entirely and is the commonest error in sorting questions.
Note the contrast with selection sort, which finds the smallest element and makes ONE swap per pass. If a question names a technique, use that one — the other earns nothing.
a[] int[15] - the fifteen integers entered by the user temp int - temporary variable used during the swap i, j int - loop variables for the passes and the comparisons sc Scanner - object used to read input