Bubble Sort

What is Bubble Sort?

Bubble sorting algorithm sort items in a list by repeatedly comparing adjacent elements and swapping them when they are out of order and this process is repeated until it sort the entire list.

Bubble Sort Animation

A picture is worth a thousand words. I found this interesting bubble sort gif file on wikimedia, which nicely explains without speaking a single word.

Bubble-sort-example-300px
Swfung8, CC BY-SA 3.0, via Wikimedia Commons

Bubble Sort Example in Java

package com.techstackjournal;

public class BubbleSort {

	public static void main(String[] args) {

		int arr[] = { 22, 15, 29, 11, 4 };
		int index = arr.length - 2;

		for (int i = 0; i <= index; i++) {
			for (int j = 0; j <= index - i; j++) {
				if (arr[j] > arr[j + 1]) {
					int temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
		}

		for (int i : arr) {
			System.out.println(i);
		}
	}

}

Output:

4
11
15
22
29

Reference:
Bubble Sort – Wikipedia

Leave a Comment