**Sorting Algorithm Tutorials - Herong's Tutorial Examples** - Version 6.01, by Dr. Herong Yang

Bubble Sort - Java Implementation

This section provides a tutorial on how to implement the Bubble Sort algorithm in Java. An implementation diagram is also provided.

Here is my Java implementation of Bubble Sort algorithm:

/** * HyArrays.java * This class contains sorting methods similar to java.util.Arrays. * All sorting methods should have a signature of * %Sort(Object[] a, int fromIndex, int toIndex) * where "fromIndex" is inclusive, and "toIndex" is exclusive. * Copyright (c) 2011 by Dr. Herong Yang, herongyang.com */ public class HyArrays { public static void bubbleSort(Object[] a, int fromIndex, int toIndex) { Object d; for (int i=toIndex-1; i>fromIndex; i--) { boolean isSorted = true; for (int j=fromIndex; j<i; j++) { if (((Comparable)a[j]).compareTo(a[j+1])>0) { isSorted = false; d = a[j+1]; a[j+1] = a[j]; a[j] = d; } } if (isSorted) break; } } }

The following diagram illustrates how this implementation works:

--17 42 53 67 ... 92 | | | | | +---+---+---------------+---+---+---+---+---+---------------+ | | | / 29 36 11 ... 24 39 | | | | fromIndex j i toIndex-1

- Elements to be sorted are stored from "fromIndex" to "toIndex-1" inclusive.
- At the beginning of each iteration of loop "i", elements from "i+1" to "toIndex-1" are sorted.
- At the beginning of each iteration of loop "i", elements from "fromIndex" to "j+1" are not sorted.
- At the end of each iteration of loop "i", element at "i" will be the element with the highest order in the un-sorted section.
- The "break" statement is there just in case when the un-sorted section happen to be already sorted.

*Last update: 2011.*

Table of Contents

Introduction of Sorting Algorithms

Java API for Sorting Algorithms

Insertion Sort Algorithm and Implementation

Selection Sort Algorithm and Implementation

►Bubble Sort Algorithm and Implementation

Bubble Sort - Algorithm Introduction

►Bubble Sort - Java Implementation

Bubble Sort - Implementation Improvements

Quicksort Algorithm and Implementation

Merge Sort Algorithm and Implementation

Heap Sort Algorithm and Implementation

Shell Sort Algorithm and Implementation