Bubble Sort Algorithm

The Bubble Sort Algorithm is a simple and widely known sorting algorithm used to sort elements in an array, list, or any other data structure. The algorithm works by repeatedly iterating through the list and comparing each adjacent pair of elements. If the elements are out of order, they are swapped, and the process continues until the entire list is sorted. Bubble Sort gets its name from the way smaller elements "bubble" to the top of the list (i.e., the beginning of the array) as larger elements "sink" to the bottom (i.e., the end of the array) during the sorting process. This algorithm has a straightforward implementation and is easy to understand, making it an excellent choice for teaching sorting concepts to beginners. However, Bubble Sort Algorithm has its limitations, as it is not the most efficient sorting algorithm for large datasets. It has a worst-case and average-case time complexity of O(n^2), where n is the number of items being sorted. This means that the algorithm's performance degrades substantially as the size of the input increases. In practical applications, other sorting algorithms such as Quick Sort, Merge Sort, or Heap Sort are often preferred due to their better performance characteristics. Despite its limitations, Bubble Sort Algorithm remains a fundamental sorting technique and serves as a great introduction to the world of algorithms and computer science.
package Sorts;

import static Sorts.SortUtils.*;

/**
 * @author Varun Upadhyay (https://github.com/varunu28)
 * @author Podshivalov Nikita (https://github.com/nikitap492)
 * @see SortAlgorithm
 */

class BubbleSort implements SortAlgorithm {
    /**
     * This method implements the Generic Bubble Sort
     *
     * @param array The array to be sorted
     *              Sorts the array in increasing order
     **/

    @Override
    public <T extends Comparable<T>> T[] sort(T[] array) {
        for (int i = 0, size = array.length; i < size - 1; ++i) {
            boolean swapped = false;
            for (int j = 0; j < size - 1 - i; ++j) {
            	if (less(array[j], array[j + 1])) {
            		swap(array, j, j + 1);
            		swapped = true;
                }
            }
            if (!swapped) {
                break;
            }
        }
        return array;
    }

    // Driver Program
    public static void main(String[] args) {

        // Integer Input
        Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
        BubbleSort bubbleSort = new BubbleSort();
        bubbleSort.sort(integers);

        // Output => 231, 78, 54, 23, 12, 9, 6, 4, 1
        print(integers);

        // String Input
        String[] strings = {"c", "a", "e", "b", "d"};
        //Output => e, d, c, b, a
        print(bubbleSort.sort(strings));

    }
}

LANGUAGE:

DARK MODE: