Recursive Bubble Sort Algorithm | Java Programs

Output:

*** Recursive Bubble Sort ***

Before Bubble Sort Algorithm:
[64, 34, 25, 12, 22, 11, 90]

After Bubble Sort Algorithm:
[11, 12, 22, 25, 34, 64, 90]

Click Here For Java Online Compiler

Solution:

/**
 *
 * @author Alee Ahmed Kolachi
 */
import java.util.Arrays;

public class RecursiveBubbleSort {

    static void bubbleSort(int myArray[], int n) {
        if (n == 1) {
            return;
        }

        // First Pass
        // Largest Element would be bubble to last.
        for (int i = 0; i < n - 1; i++) {
            if (myArray[i] > myArray[i + 1]) {
                int temp = myArray[i];
                myArray[i] = myArray[i + 1];
                myArray[i + 1] = temp;
            }
        }

        // Largest element is fixed,
        bubbleSort(myArray, n - 1);
    }

    public static void main(String[] args) {
        int myArray[] = {64, 34, 25, 12, 22, 11, 90};
        System.out.println("*** Recursive Bubble Sort ***" + "\n");
        System.out.println("Before Bubble Sort Algorithm:");
        System.out.println(Arrays.toString(myArray));
        bubbleSort(myArray, myArray.length);

        System.out.println();
        System.out.println("After Bubble Sort Algorithm:");
        System.out.println(Arrays.toString(myArray));
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon