Bubble Sort Program in Java (Ascending & Descending Order)

⚑ Direct Answer & Key Takeaway

Bubble Sort arranges an integer array in ascending or descending order by repeatedly comparing adjacent elements `arr[j]` and `arr[j+1]` and swapping them whenever they sit out of order. After each outer pass `i`, the largest element in ascending order, or smallest in descending order, settles at index `n-1-i`. Because every pass locks one terminal position, the inner loop runs only while `j < n-1-i`, sorting the entire `n`-element array in `n-1` passes.

1. How Adjacent Swapping Builds Each Pass

Think of heavier air bubbles rising to the top of a column one step at a time. In an array of `n` integers, the outer loop counter `i` tracks the pass number from `0` to `n-2`, representing `n-1` total passes. During pass `i`, the inner loop counter `j` walks from `0` up to `n-2-i` and tests whether `arr[j]` and `arr[j+1]` violate the chosen order. Whenever they do, a temporary variable `temp` swaps both elements in three assignments: save `arr[j]`, overwrite `arr[j]` with `arr[j+1]`, and copy `temp` into `arr[j+1]`. Because each pass pushes one extreme value to its final slot, the unsorted window shrinks by one index every iteration.

  • Outer loop runs `i = 0` to `i < n - 1` because placing `n - 1` elements automatically positions the first element.
  • Inner loop stops at `j < n - 1 - i` so Java never evaluates `arr[j + 1]` past index `n - 1`.
  • In ascending order, swap when `arr[j] > arr[j + 1]`; in descending order, flip the operator to `arr[j] < arr[j + 1]`.
  • Equal adjacent values (`arr[j] == arr[j + 1]`) are never swapped, keeping Bubble Sort stable.

2. Step-by-Step Dry Run on {45, 12, 78, 23, 9}

ICSE Section A frequently prints an array and asks for its exact state after Pass 1 or Pass 2. Consider `arr = {45, 12, 78, 23, 9}` with `n = 5` in ascending order. In Pass 0 (`i = 0`), `j` runs from `0` to `3`: `45 > 12` swaps to `{12, 45, 78, 23, 9}`; `45 > 78` is false; `78 > 23` swaps to `{12, 45, 23, 78, 9}`; `78 > 9` swaps to `{12, 45, 23, 9, 78}`. Notice `78` has bubbled to index `4`. In Pass 1 (`i = 1`), `j` stops at `2`, moving `45` to index `3` and leaving `{12, 23, 9, 45, 78}`. Pass 2 produces `{12, 9, 23, 45, 78}`, and Pass 3 finalizes `{9, 12, 23, 45, 78}`.

  • Pass 1 end state (`i = 0`): `{12, 45, 23, 9, 78}` with `78` fixed at the rightmost index.
  • Pass 2 end state (`i = 1`): `{12, 23, 9, 45, 78}` after comparing only indices `0..3`.
  • Pass 3 and Pass 4 finish as `{12, 9, 23, 45, 78}` and `{9, 12, 23, 45, 78}` using `4 + 3 + 2 + 1 = 10` total comparisons.

3. Switching Between Ascending & Descending in ICSE Section B

Board questions often combine sorting with a user menu, asking students to press `1` for ascending order or `2` for descending order, or to sort weight/marks arrays in reverse order. Instead of duplicating the nested loops twice, keep a single `for` loop structure and decide the swap condition inside using `choice`. Writing `(choice == 1 && arr[j] > arr[j+1]) || (choice == 2 && arr[j] < arr[j+1])` keeps the program concise and readable for examiners. You can also add a `boolean swapped` flag inside the outer loop to break early when a pass makes zero swaps, though standard ICSE marking schemes award full marks without early exit.

  • Single nested-loop block with `choice` avoids duplicate code and saves 3–4 minutes in the 2-hour paper.
  • Always display the sorted list clearly with `System.out.print` separated by spaces.
  • Read `n`, array values, and `choice` cleanly before sorting begins.

4. BubbleSortNumbers.java (Ascending & Descending Menu)

import java.util.*;

public class BubbleSortNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter number of elements: ");
        int n = sc.nextInt();
        int[] arr = new int[n];

        System.out.println("Enter " + n + " integers:");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.print("Enter 1 for Ascending or 2 for Descending: ");
        int choice = sc.nextInt();

        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - 1 - i; j++) {
                boolean needSwap = (choice == 1 && arr[j] > arr[j + 1])
                                || (choice == 2 && arr[j] < arr[j + 1]);
                if (needSwap) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }

        System.out.print("Sorted Array: ");
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter number of elements: 5
Enter 5 integers:
45 12 78 23 9
Enter 1 for Ascending or 2 for Descending: 2
Sorted Array: 78 45 23 12 9

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
nintStores total array size entered by user (Sample: 5)
arr[]int[]1D array storing unsorted and sorted integers (Sample: {45, 12, 78, 23, 9})
choiceintMenu flag: 1 for ascending, 2 for descending (Sample: 2)
iintOuter loop pass counter from 0 to n - 2 (Sample: 0 to 3)
jintInner loop index comparing adjacent pair arr[j] and arr[j+1] (Sample: 0 to 3)
tempintTemporary swap variable holding arr[j] during exchange (Sample: 45)
🎯 1-on-1 Live Mentorship & Free Study Kit

Master ICSE Bubble Sort & VDTs in a 1-on-1 Live Java Class

Practice live BlueJ coding, trace Section A pass-by-pass dry runs, and learn how ICSE examiners grade 15-mark array sorting programs with personalized mentor feedback.

πŸ’¬ WhatsApp Now
πŸ”’ Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Writing `j < n - i` instead of `j < n - 1 - i`, which throws `ArrayIndexOutOfBoundsException` when Java accesses `arr[j + 1]` at the last index.
  • Avoid Mistake: Swapping directly via `arr[j] = arr[j + 1]; arr[j + 1] = arr[j];` without `temp`, overwriting `arr[j]` and duplicating the same number.
  • Avoid Mistake: Using Selection Sort logic (`arr[i] > arr[j]`) inside Bubble Sort loops; CISCE examiners deduct logic marks if adjacent pairs `arr[j]` and `arr[j + 1]` are not compared.
  • Examiner / Mentor Tip: Write the Variable Description Table immediately after the program in Section Bβ€”every missing key variable like `temp` or `choice` can cost 1–2 marks.
  • Examiner / Mentor Tip: When asked to sort an array of fixed size like 10 or 15 in the board paper, declare `int[] arr = new int[10];` directly as specified instead of asking for `n`.
  • Examiner / Mentor Tip: Remember the comparison formula `n * (n - 1) / 2`: for 5 numbers, nested loops always execute `5 * 4 / 2 = 10` comparisons without early exit.

7. Interactive Concept Check Quiz

Question: An integer array {34, 15, 29, 8, 42} is sorted in descending order using Bubble Sort. What is the array state immediately after Pass 1 (i = 0)?

8. Frequently Asked Questions

Does ICSE Class 10 require an optimized Bubble Sort with a swapped flag?
No, the standard nested for-loop Bubble Sort without a boolean flag earns full marks in CISCE board exams. Examiners mainly check correct loop bounds (i < n - 1 and j < n - 1 - i), accurate adjacent comparison, three-step swapping with temp, and a complete Variable Description Table. Adding a swapped flag is optional and useful only if asked to minimize passes.
How is Bubble Sort different from Selection Sort in ICSE board papers?
Bubble Sort compares adjacent elements arr[j] and arr[j + 1] and swaps repeatedly during every inner pass, pushing the largest or smallest value to the end. Selection Sort tracks the minimum or maximum index in minIdx across the unsorted portion and performs only one swap per outer pass, making Selection Sort perform fewer write operations overall.
Can I sort negative numbers and duplicates with the same Bubble Sort code?
Yes, relational operators > and < work identically for negative integers, zero, and positive integers in Java. Duplicate values are handled safely because strict inequality (> or <) skips swapping when arr[j] == arr[j + 1]. That preserves the original relative positions of equal elements and prevents unnecessary assignments inside the inner loop.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class