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[] = {  
  5.    12,  
  6.    9,  
  7.    4,  
  8.    99,  
  9.    120,  
  10.    1,  
  11.    3,  
  12.    10  
  13.   };  
  14.   System.out.println("\n\n       RoseIndia\n\n");  
  15.   System.out.println("       Selection Sort\n\n");  
  16.   System.out.println("Values Before the sort:\n");  
  17.   for (i = 0; i < array.length; i++)  
  18.    System.out.print(array[i] + "  ");  
  19.   System.out.println();  
  20.   bidirectionalBubble_srt(array, array.length);  
  21.   System.out.print("Values after the sort:\n");  
  22.   for (i = 0; i < array.length; i++)  
  23.    System.out.print(array[i] + "  ");  
  24.   System.out.println();  
  25.   System.out.println("PAUSE");  
  26.  }  
  27.  public static void bidirectionalBubble_srt(int array[], int n) {  
  28.   int j;  
  29.   int st = -1;  
  30.   while (st < n) {  
  31.    st++;  
  32.    n--;  
  33.    for (j = st; j < n; j++) {  
  34.     if (array[j] > array[j + 1]) {  
  35.      int T = array[j];  
  36.      array[j] = array[j + 1];  
  37.      array[j + 1] = T;  
  38.     }  
  39.    }  
  40.    for (j = n; --j >= st;) {  
  41.     if (array[j] > array[j + 1]) {  
  42.      int T = array[j];  
  43.      array[j] = array[j + 1];  
  44.      array[j + 1] = T;  
  45.     }  
  46.    }  
  47.   }  
  48.  }  
  49. }   
Output
 
d