SUNDAY, 12 JULY 2026
Guide For School logo Guide For SchoolStudy Guide For Students On Java Programming
Physics | Chemistry | Mathematics
ICSE | ISC | CBSE
Guide For School logo Guide For SchoolICSE and ISC Resources

Bubble Sort Program in Java and Python

02 July 2016

Bubble sort program with algorithm, explanation, Java solution and simple Python solution for ICSE and ISC students.

Question:

Write a program to input an array of integers and sort it in ascending order using the Bubble Sort algorithm.

INPUT: Enter the number of elements: 8 Enter element 1: 6 Enter element 2: 5 Enter element 3: 3 Enter element 4: 1 Enter element 5: 8 Enter element 6: 7 Enter element 7: 2 Enter element 8: 4 OUTPUT: The Original array is: 6 5 3 1 8 7 2 4 The Array Sorted in Ascending order is: 1 2 3 4 5 6 7 8
Bubble sort example animation
Bubble sort repeatedly compares adjacent elements and moves the larger value towards the end.

Algorithm:

Step 1: Start.

Step 2: Accept the number of elements n and store the elements in array A.

Step 3: Display the original array before sorting.

Step 4: Set a flag variable before each pass to assume that no swap is required.

Step 5: Run the outer loop from pass 0 to n - 2.

Step 6: In each pass, run the inner loop from index 0 to n - 2 - pass.

Step 7: Compare adjacent elements A[j] and A[j + 1].

Step 8: If A[j] is greater than A[j + 1], swap them using a temporary variable and set the flag.

Step 9: After each pass, the largest unsorted element settles at the end, so reduce the next pass range by one.

Step 10: If a complete pass has no swap, stop sorting early because the array is already sorted.

Step 11: Display the sorted array.

Step 12: Stop.

Explanation:

Bubble sort works by comparing two neighbouring elements at a time. If the left element is greater than the right element, the two values are swapped so that the larger value moves towards the right side of the array.

The outer loop counts the passes. After the first pass, the largest element reaches the last position. After the second pass, the second largest reaches the second last position. This is why the inner loop condition uses n - 1 - i; already settled elements are not compared again.

The flag variable improves the algorithm. At the beginning of every pass, the program assumes that the array may already be sorted. If no swap occurs during that pass, the flag remains unchanged and the loop stops early.

The printArray() method is used to display both the original and sorted arrays. Keeping printing in a separate method avoids repeating the same loop.

Bubble sort works by repeatedly comparing neighbouring elements. If two adjacent values are in the wrong order, they are swapped. After one full pass, the largest unsorted value moves to its correct position at the end of the array. The next pass can therefore ignore that last position. The program uses nested loops to repeat these comparisons until the array becomes sorted. The temporary variable is needed during swapping so that one value is not lost while the two positions exchange contents.

Java Program:

Java
/**
* The class BubbleSorting inputs an array and sorts the elements in ascending order
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.util.*;
class BubbleSorting
{
    void BubbleSort(int A[]) // function to sort an array in ASCENDING ORDER implementing bubble sort technique
    {
        int n = A.length; // finding size of the array
        int c = 0, f = 1;
        for(int i=0; i<n-1 && f==1; i++)
        {
            f = 0;
            for(int j=0; j<n-1-i; j++)
            {
                if(A[j] > A[j+1]) // for descending use if(A[j] < A[j+1])
                {
                    c = A[j];
                    A[j] = A[j+1];
                    A[j+1] = c;
                    f = 1; // setting f = 1 when swapping takes place i.e. when array is not yet sorted
                }
            }
            if(f == 0) // breaking out of the loop when array is sorted
            break;
        }
        System.out.println("The Array Sorted in Ascending order is : ");
        printArray(A);
    }

    /* Explanation of the above code:
    * 'i' loop is for denoting the step numbers.
    * The maximum number of steps in which any array would get sorted is 'n-1'.
    * So if there are 5 elements in the array, then that array will take a maximum of 4 steps to get sorted.
    * f=1 would mean that the array is not sorted.
    * So f==1 condition is to continue sorting till the array is not sorted.
    * f=0 would mean that the array is sorted.
    * 'j' loop is for comparing one element with the next element i.e. element at index 0 with 1, 1 with 2 etc
    * With every step, the highest element of that step settles down at
    * its correct position i.e. the end of the array, so we need not include it in next step.
    * So, the number of comparisons in every step reduces by one.
    * If there are 5 elements then this is how comparisons take place:
    * In step 1 : 0-1, 1-2, 2-3 and 3-4
    * In step 2 : 0-1, 1-2 and 2-3
    * In step 3 : 0-1 and 1-2
    * In step 4 : 0-1
    * For this reason we have 'j<n-1-i' where as 'i' increases in every step, no of comparisons decreases by 1
    * Before the beginning of every step, we are setting f=0, assuming that the array is sorted.
    * If the array is not sorted, we are swapping the elements, and setting f=1,
    * denoting that the array is not yet sorted and needs sorting.
    * So, if no swapping takes place, that would mean that the array is sorted and the value of f will remain 0.
    * In this case, we are breaking out of the loop and printing the sorted array.
    */

    void printArray(int A[]) // function for printing an array
    {
        int n = A.length;
        for(int i=0; i<n; i++)
        {
            System.out.print(A[i]+ " ");
        }
        System.out.println();
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        BubbleSorting ob = new BubbleSorting();
        System.out.print("Enter the number of elements : ");
        int n = sc.nextInt();
        int A[] = new int[n];
        for(int i=0; i<n; i++)
        {
            System.out.print("Enter element "+(i+1)+" : ");
            A[i] = sc.nextInt();
        }
        System.out.println("The Original array is : ");
        ob.printArray(A);
        ob.BubbleSort(A);
    }
}

Equivalent Python Program:

Python
def bubble_sort(A):
    n = len(A)

    for i in range(n - 1):
        swapped = 0

        # Compare adjacent elements in the unsorted part of the list.
        for j in range(0, n - 1 - i):
            if A[j] > A[j + 1]:
                temp = A[j]
                A[j] = A[j + 1]
                A[j + 1] = temp
                swapped = 1

        # If no swap occurs in a pass, the list is already sorted.
        if swapped == 0:
            break


def print_array(A):
    for i in range(len(A)):
        print(A[i], end=" ")
    print()


n = int(input("Enter the number of elements: "))
A = []

# Store the input values one by one in the list.
for i in range(n):
    value = int(input("Enter element " + str(i + 1) + ": "))
    A.append(value)

print("The Original array is:")
print_array(A)

bubble_sort(A)

print("The Array Sorted in Ascending order is:")
print_array(A)

Output:

Enter the number of elements: 8 Enter element 1: 6 Enter element 2: 5 Enter element 3: 3 Enter element 4: 1 Enter element 5: 8 Enter element 6: 7 Enter element 7: 2 Enter element 8: 4 The Original array is: 6 5 3 1 8 7 2 4 The Array Sorted in Ascending order is: 1 2 3 4 5 6 7 8

Leave a Reply

Your email address will not be published. Comments are reviewed before appearing publicly.

Send a comment or correction

Study smarter

Everything you need for ICSE and ISC Computer

Programs, revision notes, solved papers and practical guidance—organized for quick study.

Browse all resources →