Bi-Directional Bubble Sort in Java

Introduction
  • In this blog, I am going to explain the program for Bidirectional Bubble Sort in Java
Software Requirements
  • Java, Notepad
Programming
  1. public class BidirectionalBubbleSort{  
  2.     public static void main(String a[]){  
  3.         int i;  
  4.         int array[] = {12,9,4,99,120,1,3,10};  
  5.         System.out.println("\n\n       RoseIndia\n\n");  
  6.         System.out.println("       Selection Sort\n\n");  
  7.         System.out.println("Values Before the sort:\n");  
  8.         for(i = 0; i < array.length; i++)  
  9.             System.out.print( array[i]+"  ");  
  10.         System.out.println();  
  11.         bidirectionalBubble_srt(array, array.length);  
  12.         System.out.print("Values after the sort:\n");  
  13.         for(i = 0; i <array.length; i++)  
  14.             System.out.print(array[i]+"  ");  
  15.         System.out.println();  
  16.         System.out.println("PAUSE");  
  17.     }  
  18.   
  19.     public static void bidirectionalBubble_srt(int array[], int n){  
  20.         int j;  
  21.         int st = -1;  
  22.         while (st <  n) {  
  23.             st++;  
  24.             n--;  
  25.             for (j = st; j <  n; j++) {  
  26.                 if (array[j] > array[j + 1]) {  
  27.                     int T = array[j];  
  28.                     array[j] = array[j + 1];  
  29.                     array[j + 1] = T;  
  30.                 }  
  31.             }  
  32.             for (j =  n; --j >= st;) {  
  33.                 if (array[j] > array[j + 1]) {  
  34.                     int T = array[j];  
  35.                     array[j] = array[j + 1];  
  36.                     array[j + 1] = T;  
  37.                 }  
  38.             }  
  39.         }  
  40.     }  

Output
 
Ebook Download
View all
Learn
View all