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

The outer loop controls the number of passes and the inner loop compares adjacent elements, swapping them if the left is greater, so the largest element bubbles to the end each pass, sorting the array in ascending order.

Quick Links to Explore