BUBBLE SORT PROGRAM IN JAVA

 /*  
 Arraging set of elements in increment order using   
 Bubble Sort in java;   
 author:www.examplesinjava.blogspot.com  
     www.ccoding.blogspot.com  
 */  
 import java.util.*;   
 class BubbleSort  
 {  
      static Scanner in = new Scanner(System.in);   
      public static void main(String[]args)  
           {  
           System.out.println("Enter your Array Size");  
           int n = in.nextInt();   
           int[]arr = new int[n];   
           fillArray(arr,n);   
           bubbleSort(arr,n);  
           printArray(arr,n);   
           }  
 // Bubble sort method   
      static void bubbleSort(int[]a,int n)  
           {  
           for(int out=0;out<n-1;out++)                 
                {  
                for(int in=0;in<n-1;in++) // in<in-1-out can use this condition too to reduce iteration.  
                     {  
                     if(a[in]>a[in+1]) // sending max element to last.  
                          {  
                          int temp = a[in];  
                          a[in]=a[in+1];  
                          a[in+1]=temp;   
                          }  
                     }  
                }  
           }  
      static void fillArray(int []a, int n)// fill array Method  
           {  
                System.out.println("Enter Your Elements");  
                for(int i=0;i<n;i++)  
                     a[i]=in.nextInt();   
           }  
      static void printArray(int []a, int n)// print array Method.  
           {  
                System.out.print("Array Elements = ");  
                for(int i=0;i<n;i++)  
                     System.out.print(a[i]+"\t");  
                System.out.println(" ");  
           }  
 }  

Post a Comment

0 Comments