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 signiture of
* %Sort(Object[] a, int fromIndex, int toIndex)
* where "fromIndex" is inclusive, and "toIndex" is exclusive.
* Copyright (c) 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:

• 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.

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 signiture of
* %Sort(Object[] a, int fromIndex, int toIndex)
* where "fromIndex" is inclusive, and "toIndex" is exclusive.
* Copyright (c) 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