Bubble Sort

// This bubble sort will sort everything from
// smallest to largest or largest  to smallest 

import java.io.*;

class BubbleSortTest {
public static void main (String[] args) {
int[] a={5,2,9,1,23};
    
   // Ascending Order
 // k starts at the end of the Array
// As it is decremented all indexes greater
// then it are sorted
     for(int k=a.length-1;k>0;k--){
// The inner loop starts at the beginning of
// the array and compares each value next to each
// other. If the value is greater then they are
// swapped
        for(int m=0;m<km++)
// To change sort to Descending change to <
            if(a[m]>a[m+1]){
                int temp1=a[m];
                a[m]=a[m+1];
                a[m+1]=temp1;
            }
        
            
        }
        }
           for(int k=0;k<a.length;k++){
       System.out.print(" "+a[k]);  
           }

            System.out.println(" ");

    // descening Order
    for(int i=a.length-1;i>0;i--){
     
    for(int j=0;j<i;j++){
       
        if(a[j]<a[j+1]){
            int temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp;
        }
       
    }

   }
     for( int i=0;i<a.length;i++){
               System.out.print(" "+a[i]);
            }

     
  
     
}
}

Comments