Bubble Sort


  • Time complexity - O(n^2)  || Space Complexity - O(1)
  • Bubble sort is an inplace sorting algorithm, that means we do not any extra space while bubble sorting

public class Main {
    public static void main(String[] args) throws Exception {
        int[] arr={1,4,4,5,6,2,3,90,120,43,0};
        
        System.out.println("UnSorted Array :");
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
        }
        System.out.println();
        // bubble sort
        for(int i=0;i<arr.length-1;i++){ // iterates through first to last cell
            for(int j=0;j<arr.length-1-i;j++){ // inner loop controls swapping and extent to which swapping is to be performed in array
                if(arr[j]>arr[j+1]){
                    int temp = arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=temp;
                }
            }
            // after each iteration we get a largest element "bubble up"
            System.out.println((i+1)+"st largest :"+arr[arr.length-1-i]);
        }
        System.out.println();
        System.out.println("Sorted Array in increasing order:");
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
        }
    }
}


Output:

UnSorted Array :
1 4 4 5 6 2 3 90 120 43 0 
1st largest :120
2st largest :90
3st largest :43
4st largest :6
5st largest :5
6st largest :4
7st largest :4
8st largest :3
9st largest :2
10st largest :1

Sorted Array in increasing order:
0 1 2 3 4 4 5 6 43 90 120 


Comments

Popular posts from this blog

Binary Heap - Introduction

Divide and Conquer - Introduction