Implementing Bubble Sort Algorithm using Java Program


Implementing Bubble Sort Algorithm in Java

Bubble sort algorithm compares the adjacent elements in an array and swaps them if they're in the wrong order. To implement BubbleSort in Java, you need to make use of two nested for loop, you do not additional memory as we save the sorted data in the same array.

package org.code2care.java.sorting.algo;


import java.util.Arrays;

/**
 * BubbleSort Example in Java
 *
 * Author: Code2care.org
 * Date: 28 April 2023
 * Version: v 1.0
 *
 */
public class BubbleSortJavaExample {

    public static void main(String[] args) {

        //Unsorted Array
        int[] unsortedArray = {4, 99, 2, 11, 34, 67, 54, 12, 45, 245, 234, 12, 200};
        BubbleSortJavaExample bubbleSort = new BubbleSortJavaExample();

        //Note: new array or Arrays.toString is not needed - added just for clarity
        int[] sortedArray = bubbleSort.bubbleSortAlgorithm(unsortedArray);
        System.out.println(Arrays.toString(sortedArray));
    }

    /**
     *
     * @param arrayOfNumbers: unsorted array as provided to sort
     * @return: sorted array using bubble sort
     */
    public int[] bubbleSortAlgorithm(int[] arrayOfNumbers) {

        int arrayLength = arrayOfNumbers.length;
        int tempVariable = 0;

        for (int outerIndex = 0; outerIndex < arrayLength - 1; outerIndex++) {

            for (int innerIndex = 0; innerIndex < arrayLength - outerIndex - 1; innerIndex++) {

                int elementN = arrayOfNumbers[innerIndex];
                int elementNPlus1 = arrayOfNumbers[innerIndex + 1];

                if (elementN > elementNPlus1) {
                    tempVariable = arrayOfNumbers[innerIndex];
                    arrayOfNumbers[innerIndex] = arrayOfNumbers[innerIndex + 1];
                    arrayOfNumbers[innerIndex + 1] = tempVariable;
                }
            }
        }

        return arrayOfNumbers;
    }
}

Output:

[2, 4, 11, 12, 12, 34, 45, 54, 67, 99, 200, 234, 245]


ComplexityNotation
Time complexity (worst-case)O(n^2)
Time complexity (average-case)O(n^2)
Time complexity (best-case)O(n)
Space complexityO(1)

It is advised not to make use of bubble sort apart from learning as there are other algorithms like Merge sort or Quick sort that are more efficient.

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap