Bubble Sort Implementation

This program sorts an array using bubble sort algorithm.

Problem Statement

Write a Java program to sort an integer array using bubble sort.

Source Code

1 public class BubbleSort {
2 public static void main(String[] args) {
3 int[] arr = {64, 34, 25, 12, 22, 11, 90};
4 for(int i=0; i<arr.length-1; i++) {
5 for(int j=0; j<arr.length-i-1; j++) {
6 if(arr[j] > arr[j+1]) {
7 int temp = arr[j];
8 arr[j] = arr[j+1];
9 arr[j+1] = temp;
10 }
11 }
12 }
13 System.out.print("Sorted array: ");
14 for(int num : arr) System.out.print(num + " ");
15 }
16 }

Program Output

Sorted array: 11 12 22 25 34 64 90

Explanation

Outer loop controls passes. - Inner loop compares adjacent elements. - Swap occurs if left element is greater. - Largest element bubbles to end each pass. - Together sorts array in ascending order. Conclusion: Shows how bubble sort can be implemented in arrays.

Quick Links to Explore