Bubble sort

largest Bubble (element ) ko end bhej and sorting kar

  • comparison sort method

alt text

simple comparison-based sorting algorithm where each pair of adjacent elements is compared, and if they are in the wrong order, they are swapped.

The process repeats until no swaps are needed, indicating that the array is sorted. It’s called “bubble” sort because the largest element “bubbles” to the top in each iteration.

Steps

  • Start from the first element and compare the current element with the next element.
  • If the current element is greater than the next element, swap them.
  • Move to the next pair of elements and repeat the comparison.
  • Continue this process for each pair of elements in the array.
  • After the first pass, the largest element will have “bubbled” to the last position.
  • Repeat the process for the rest of the array (ignoring the last sorted elements in subsequent passes) until no swaps are made, meaning the array is sorted

code:

public class main {    
    public static void main (String arg[]){
        int arr[] = {1,2,3,4,5,6};
        for (int i=0; i<arr.length-i; i++)
            for (int j = 0 ; j < arr.length - i - 1; j++){
                if (arr[j] > arr [j + 1] ) {
                    int temp = arr[j];
                    arr[j] = arr [j + 1];
                    arr[j + 1] = temp;
                }
            }
        System.out.println("Sorted array:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

code with user input

import java.util.Scanner;

public class Main {    
    public static void main(String arg[]){
        Scanner sc = new Scanner(System.in);
        
        // Ask user for the size of the array
        System.out.print("Enter the number of elements in the array: ");
        int n = sc.nextInt();
        
        // Declare an array of size n
        int arr[] = new int[n];
        
        // Accept array elements from user input
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        
        // Bubble sort algorithm
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }

        // Print the sorted array
        System.out.println("Sorted array:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        
        sc.close();
    }
}

Time and space complexity

alt text