How to Implement Bubble Sort in Java Program ?

  Java Interview Q&A

Dear readers, we can create a Java program to sort array elements using bubble sort. The bubble sort algorithm is known as the simplest sorting algorithm.

In the bubble sort algorithm, the array is traced from the first element to the last element. Here, the current element is compared with the next element. If the current element is greater than the next element, it is swapped.

Example 1 : Bubble Sort in Java

public class BubbleSortExample {
	static void bubbleSort(int[] arr) {
        int n = arr.length;
        int temp = 0;
         for(int i=0; i < n; i++){
                 for(int j=1; j < (n-i); j++){
                          if(arr[j-1] > arr[j]){
                                 //swap elements
                                 temp = arr[j-1];
                                 arr[j-1] = arr[j];
                                 arr[j] = temp;
                         }
                        
                 }
         }

    }
    public static void main(String[] args) {
                int arr[] ={3,60,35,2,45,320,5};
               
                System.out.println("Array Before Bubble Sort");
                for(int i=0; i < arr.length; i++){
                        System.out.print(arr[i] + " ");
                }
                System.out.println();
                
                bubbleSort(arr);//sorting array elements using bubble sort
               
                System.out.println("Array After Bubble Sort");
                for(int i=0; i < arr.length; i++){
                        System.out.print(arr[i] + " ");
                }
 
        }
}

Output:

Array Before Bubble Sort
3 60 35 2 45 320 5 
Array After Bubble Sort
2 3 5 35 45 60 320

Example 2 : Bubble Sort on Strings

In the following example we have stored the strings in a string string and we are using nested for loops to compare adjacent strings in the array, if they are not in order then we can make them using a temporary string variable temp. Doing swap.

Here we are using the ComparTo () method to compare adjacent strings.

public class JavaExample {
   public static void main(String []args) {
	String str[] = { "Ajeet", "Steve", "Rick", "Becky", "Mohan"};
	String temp;
	System.out.println("Strings in sorted order:");
	for (int j = 0; j < str.length; j++) {
   	   for (int i = j + 1; i < str.length; i++) {
		// comparing adjacent strings
		if (str[i].compareTo(str[j]) < 0) {
			temp = str[j];
			str[j] = str[i];
			str[i] = temp;
		}
	   }
	   System.out.println(str[j]);
	}
   }
}

Output:

Strings in sorted order:
Ajeet
Recky
Mohan
Rick
Steve

Read Here Complete Java Tutorial – Click Here

LEAVE A COMMENT