Bubble Sort Algorithm

Bubble Sort Program

  • It is a sorting algorithm
  • This algorithm is not efficient in sorting hence not used much
  • Still its a good idea to understand
 
Java Code
  import java.util.*;

    class BubbleSort {
    
      public int[] sort(int a[]) {
        boolean isSorted = false;
    
        while (!isSorted) {
          isSorted = true;
          for (int i = 0; i < a.length - 1; i++) {
            if (a[i] > a[i + 1]) {
              swap(a, i, i + 1);
              isSorted = false;
            }
          }
        }
    
        return a;
      }
    
      public static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
      }
    
      public static void main(String args[]) {
        BubbleSort bS = new BubbleSort();
    
        int[] element = {6, 7, 3, 2, 1, 9, 4};
        System.out.print("Original array: ");
        for(Integer i : element){
            System.out.print(i + "  ");
        }
        int[] result = bS.sort(element);
        System.out.println();
        System.out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - -");
    
        System.out.print("Sorted array: ");
        for(Integer i : result){
        System.out.print(i + "  ");
        }
      }
  }
 
Output
 

Original array: 6 7 3 2 1 9 4 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - 

Sorted array: 1 2 3 4 6 7 9 

### Complexity Analysis * **Time Complexity**: O(N^2) in worst case (already sorted in reverse) and O(N) in best case (already sorted). * **Space Complexity**: O(1) as it is an in-place sorting algorithm. ### Complexity Analysis * **Time Complexity**: O(N^2) * **Space Complexity**: O(1)

Share Your Thoughts

Read More....
Heap Sort
Insertion Sort
Merge Sort
Quick Sort
Radix Sort
Browse all Arrays articles

Stay Ahead

Only insights that save you time or money. No fluff, ever.

Stay Ahead

Only insights that save you time or money. No fluff.