Bubble Sort in java

On-campus and online computer science courses to Learn the basic concepts of Computer Science.This tutorial will cover c ,c++, java, data structure and algorithm,computer graphics,microprocessor,analysis of algorithms,Digital Logic Design and Analysis,computer architecture,computer networks,operating system.
code in java:
import java.util.*;
class BubbleSort 
{
  public static void main(String []args) 
  {
    int n;
    Scanner in = new Scanner(System.in);
 
    System.out.println("Enter total numbers of elements: ");
    n = in.nextInt();
 
    int array[] = new int[n];
    for (int i=0;i<n; i++)
    {
     System.out.println("Enter"+ i+ "number : ");
        array[i] = in.nextInt();
    }
    bubblesort(array,n);
    System.out.println("After sorting: ");
    for (int i=0;i<n; i++) 
      System.out.println(array[i]);
  }
// method for bubble sort
  public static void bubblesort(int [ ] array,int n) 
  {
   for (int i=0;i<n-1; i++) 
   {
       for (int j=0; j<n-1; j++) 
       {
         if (array[j] > array[j+1]) /* For descending order use < */
         {
           int swap       = array[j];
           array[j]   = array[j+1];
           array[j+1] = swap;
         }
       }
     }
   }
}
output:-
Enter total numbers of elements: 5
Enter 0 number : 29
Enter 1 number : 21
Enter 2 number : 64
Enter 3 number : 02
Enter 4 number : 56
After sorting: 
2  21  29  56  64  

Analysis:
Best case - 0(n)
when the array is already sorted, the program will execute only for one pass which accounts for only
(n-1) comparisons. Hence it will end up in having efficiency of 0(n).
 Worst case - 0(n^2)
when the array is reverse sorted. The effect of 'exchange' mechanism is not there in this case as it has to execute for all passes. Hence it works very similar to classical bubble sort with efficiency of 0(n^2)
Average case - 0(n^2)
For average case even though the comparisons would be less but it gives efficiency of 0(n^2) only.

0 comments: