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

Last update: 2011.

Table of Contents

 About This Book

 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 - Performance

 Bubble Sort - Implementation Improvements

 Quicksort Algorithm and Implementation

 Merge Sort Algorithm and Implementation

 Heap Sort Algorithm and Implementation

 Shell Sort Algorithm and Implementation

 Performance Summary of Java Implementations

 References

 PDF Printing Version