Java Program for Recursive Bubble Sort


Following is the Java Program for Recursice Bubble Sort −

Example

 Live Demo

import java.util.Arrays;
public class Demo{
   static void bubble_sort(int my_arr[], int len_arr){
      if (len_arr == 1)
      return;
      for (int i=0; i<len_arr-1; i++)
      if (my_arr[i] > my_arr[i+1]){
         int temp = my_arr[i];
         my_arr[i] = my_arr[i+1];
         my_arr[i+1] = temp;
      }
      bubble_sort(my_arr, len_arr-1);
   }
   public static void main(String[] args){
      int my_arr[] = {45, 67, 89, 31, 63, 0, 21, 12};
      bubble_sort(my_arr, my_arr.length);
      System.out.println("The array after implementing bubble sort is ");
      System.out.println(Arrays.toString(my_arr));
   }
}

Output

The array after implementing bubble sort is
[0, 12, 21, 31, 45, 63, 67, 89]

A function named 'Demo' contains the function to perform bubble sort. If the length of the array is 1, then the array is returned. Otherwise, the array is iterated over and if the element at the first place is greater than the element at the next position, the elements are swapped.

After the first pass, the largest element would have been fixed, and the bubble sort is called on all elements except the largest once. In the main function, the array is defined and it is passed as a parameter to the bubble sort function.

Updated on: 07-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements