Skip to main content

Generic Bubble Sort Java Program

In this post we’ll see how to write a Bubble Sort program as a Generic class in Java which can be used with arrays of different data types.

Bubble Sort- Java Generic class

In the generic class used for Bubble Sort we use a bounded parameter to restrict the type to be of type Comparable. That is done as we do need to compare the elements for sorting for which compareTo() method of the Comparable is used.

import java.util.Arrays;

public class BubbleSortGeneric<T extends Comparable<? super T>> {
  T[] array;
  BubbleSortGeneric(T[] array){
    this.array = array;
  }
  
  private T[] bubbleSort(){
    for(int i = array.length; i > 1; i--){
      for(int j = 0; j < i - 1; j++){
        //if greater swap elements
        if(array[j].compareTo(array[j+1]) > 0){
          swapElements(j, array);
        }
      }            
    }
    return array;
  }
  private void swapElements(int index, T[] arr){
    T temp = arr[index];
    arr[index] = arr[index+1];
    arr[index+1] = temp;        
  }
  public static void main(String[] args) {
    Integer[] intArr = {47, 85, 62, 34, 7, 10, 92, 106, 2, 54};
    BubbleSortGeneric<Integer> bsg1 = new BubbleSortGeneric<Integer>(intArr);
    Integer[] sa1 = bsg1.bubbleSort();
    System.out.println("Sorted array- " + Arrays.toString(sa1)); 
    
    String[] strArr = {"Earl", "Robert", "Asha", "Arthur"};
    BubbleSortGeneric<String> bsg2 = new BubbleSortGeneric<>(strArr);
    String[] sa2 = bsg2.bubbleSort();
    System.out.println("Sorted array- " + Arrays.toString(sa2));
  }
}
Output
Sorted array- [2, 7, 10, 34, 47, 54, 62, 85, 92, 106]
Sorted array- [Arthur, Asha, Earl, Robert]

That's all for the topic Generic Bubble Sort Java Program. If something is missing or you have something to share about the topic please write a comment.


You may also like
  • Java Generics - Bounded Type Parameters
  • Radix Sort Java Program
  • What is In-place Algorithm
  • Java Date Difference Program
  • How to Create Custom Exception Class in Java
  • Java Multithreading Interview Questions And Answers
  • Java ConcurrentHashMap With Examples
  • Spring Bean Scopes