Sorting Algorithm Tutorials - Herong's Tutorial Examples - 6.12, by 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.sort(). * 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 HerongYang.com. All Rights Reserved. */ public class HyArrays { public static void bubbleSort(HyObject[] a, int fromIndex, int toIndex) { HyObject d; for (int i=toIndex-1; i>fromIndex; i--) { boolean isSorted = true; for (int j=fromIndex; j<i; j++) { if ((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
Note that:
In case you are using older versions of Java that support only the raw "Comparable" interface type, here is my old implementation:
/* HyArraysOld.java * This class contains sorting methods similar to java.util.Arrays.sort(). * 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) 2008 HerongYang.com. All Rights Reserved. */ public class HyArraysOld { 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; } } }
Table of Contents
Introduction of Sorting Algorithms
Java API for Sorting Algorithms
Insertion Sort Algorithm and Java Implementation
Selection Sort Algorithm and Java Implementation
►Bubble Sort Algorithm and Java Implementation
Bubble Sort - Algorithm Introduction
►Bubble Sort - Java Implementation
Bubble Sort - Implementation Improvements
Quicksort Algorithm and Java Implementation
Merge Sort Algorithm and Java Implementation
Heap Sort Algorithm and Java Implementation
Shell Sort Algorithm and Java Implementation
Sorting Algorithms Implementations in PHP
Sorting Algorithms Implementations in Perl
Sorting Algorithms Implementations in Python