bubble short Q1

  Bubble short assening order 

5 9 8 -2 1

1st titration 4 comparison 

2nd itteretion 3 comparison

and so on 

comparison = n-i;


  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.   
  17.     }  
  18.     public static void main(String[] args) {  
  19.                 int arr[] ={3,60,35,2,45,320,5};  
  20.                  
  21.                 System.out.println("Array Before Bubble Sort");  
  22.                 for(int i=0; i < arr.length; i++){  
  23.                         System.out.print(arr[i] + " ");  
  24.                 }  
  25.                 System.out.println();  
  26.                   
  27.                 bubbleSort(arr);//sorting array elements using bubble sort  
  28.                  
  29.                 System.out.println("Array After Bubble Sort");  
  30.                 for(int i=0; i < arr.length; i++){  
  31.                         System.out.print(arr[i] + " ");  
  32.                 }  
  33.    
  34.         }  









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

Comments

Popular posts from this blog

Git and Github

Java Program to Check Whether the String Consists of Special Characters