Java – Bubble Sort Algorithm

Bubble sort:

  • Sorting is the concept of arranging elements in the array either in ascending order or in descending order.
  • To sort the array, n number of algorithms is given such as Bubble Sort, Insertion Sort, and Selection Sort and so on.
  • Bubble sort is a simple sorting technique where elements can be sorted using their index.
import java.util.Scanner ;
class Demo
{
            public static void main(String[] args) {
                        Scanner scan = new Scanner(System.in);
                        System.out.print(“Enter array size : “);
                        int n = scan.nextInt();
                        int arr[ ] = new int[n];
 
                        System.out.println(“Enter ” + n + ” values : “);
                        for (int i=0 ; i<n ; i++){
                                    arr[i] = scan.nextInt();
                        }
                       
                        System.out.println(“Before sort : “);
                        for(int ele :  arr){
                                    System.out.print(ele + “\t”);
                        }
                        System.out.println();
 
                        for (int i=0 ; i<n-1 ; i++)
                        {
                                    for (int j=0 ; j<n-1-i ; j++ )
                                    {
                                                if(arr[j] > arr[j+1])
                                                {
                                                            int temp = arr[j];
                                                            arr[j] = arr[j+1];
                                                            arr[j+1] = temp;
                                                }
                                    }
                        }
                        System.out.println(“After sort : “);
                        for(int ele :  arr){
                                    System.out.print(ele + “\t”);
                        }
                        System.out.println();
            }
}
Scroll to Top