Design a class called BubbleSort that is similar to the class SelectionSort given in Display 6.11. The class BubbleSort will be used in the same way as the class SelectionSort, but it will use the bubble sort algorithm.
The bubble sort algorithm checks all adjacent pairs of elements in the array from the beginning to the end and interchanges any two elements that are out of order. This process is repeated until the array is sorted. The algorithm is as follows:
Bubble Sort Algorithm to Sort an Array a
Repeat the following until the array a is sorted:
for (index = 0; index < a.length – 1; index++)
if (a[index] > a[index + 1])
Interchange the values of a[index] and a[index + 1].
The bubble sort algorithm is good for sorting an array that is “almost sorted.” It is not competitive with other sorting methods for most other situations.
Program:
public class Main
{
public static void main(String args[])
{
int[] elements = { 159, 77, 543, 38, 19, 115, 93};
System.out.println("Un-sorted array elements are:");
for(int i = 0; i < elements.length; i++)
System.out.print(elements[i] + " ");
System.out.println();
BubbleSort sorter = new BubbleSort();
sorter.sort(elements);
System.out.println("\nAscending sorted array elements by using bubble sort:");
for(int i = 0; i < elements.length; i++)
System.out.print(elements[i] + " ");
}
}
class BubbleSort
{
public void sort(int[] index)
{
for(int outer = index.length - 1; outer > 0; outer--)
{
for(int inner = 0; inner < outer; inner++)
{
if(index[inner] > index[inner + 1])
{
int temp = index[inner];
index[inner] = index[inner + 1];
index[inner + 1] = temp;
}
}
}
}
}
Output of the program:
Un-sorted array elements are:
159 77 543 38 19 115 93
Ascending sorted array elements by using bubble sort:
19 38 77 93 115 159 543