Bubble Sort in Java
--
Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left to right. In this sorting algorithm, adjacent elements are swapped when they are present in the wrong order. Thus, initially, the elements of bigger values are placed at their correct position, then the elements of smaller values. The same phenomenon happens in a water tank too, bubbles of bigger size come out first, then the bubbles of smaller size. Hence, this sorting algorithm is called bubble sort.
Algorithm and Pseudo Code
start BubbleSort(array)
for all elements of the input array
if array[index] > array[index + 1]
swap(array[index], array[index + 1])
terminate if
terminate for
return array
terminate BubbleSort
Java Program
The following Java program implements Bubble sort on the basis of pseudo-code written above.
FileName: BubbleSortExample.java
public class BubbleSortExample
{
// method implementing the bubble sort algorithm
static void bubbleSort(int a[], int start, int end)
{
// outer loop iterates over elements of the array
for(int i = start; i < end — 1; i++)
{
// inner loop does the swapping of elements that are
// present in wrong order.
for(int j = 0; j < end — i — 1; j++)
{
if(a[j] > a[j + 1])
{
// found that current element
// is greater than the next element
// hence do the swapping
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
// main method
public static void main(String argvs[])
{
// given input array
int a[] = {67, 78, 34, 12, 30, 6, 9, 21};
// calculating size of the array
int size = a.length;
System.out.println(“The array before sorting is: “);
for(int i = 0; i < size; i++)
{
System.out.print(a[i] + “ “);
}
System.out.println(“\n”);
// invoking method bubbleSort()
bubbleSort(a, 0, size);
System.out.println(“The array after sorting is: “);
// displaying the sorted array
for(int i = 0; i < size; i++)
{
System.out.print(a[i] + “ “);
}
}
}