bubble-sort-java

Bubble Sort Java

Bubble Sort in Java

We can make a java program to sort exhibit components utilizing bubble sort. Air pocket sort calculation is known as the easiest arranging calculation.

In air pocket sort calculation, cluster is navigated from first component to last component. Here, current component is contrasted and the following component. On the off chance that current component is more prominent than the following component, it is traded.

  1. public class BubbleSortExample {
  2.     static void bubbleSort(int[] arr) {
  3.         int n = arr.length;
  4.         int temp = 0;
  5.          for(int i=0; i < n; i++){
  6.                  for(int j=1; j < (n-i); j++){
  7.                           if(arr[j-1] > arr[j]){
  8.                                  //swap elements
  9.                                  temp = arr[j-1];
  10.                                  arr[j-1] = arr[j];
  11.                                  arr[j] = temp;
  12.                          }
  13.                  }
  14.          }
  15.     }
  16.     public static void main(String[] args) {
  17.                 int arr[] ={3,60,35,2,45,320,5};
  18.                 System.out.println(“Array Before Bubble Sort”);
  19.                 for(int i=0; i < arr.length; i++){
  20.                         System.out.print(arr[i] + ” “);
  21.                 }
  22.                 System.out.println();
  23.                 bubbleSort(arr);//sorting array elements using bubble sort
  24.                 System.out.println(“Array After Bubble Sort”);
  25.                 for(int i=0; i < arr.length; i++){
  26.                         System.out.print(arr[i] + ” “);
  27.                 }
  28.         }
  29. }

Output:

Array Before Bubble Sort
3 60 35 2 45 320 5 
Array After Bubble Sort
2 3 5 35 45 60 320