Thursday, 3 March 2016

Optimized Bubble Sort using Java .....

Quick Logic - In bubble sort we are compairing adjacent elements, swap them if we need to and this                          will continue upto (N-1) passes .So optimized bubble sort will be most efficient if the                          array is already sorted or almost sorted.

Optimization Logic - We are checking that if two continues passes of the bubble sort are same then                            we don't have to continue further because array has already become sorted till now.

here is the code....


       
public class OptimizedBubbleSort {

 static int[] arr = {
  1,
  2,
  3,
  4,
  5,
  6,
  70,
  18,
  9
 };
 static boolean[] swapFlag = new boolean[arr.length - 1]; //to keep track that in each pass swap happens or not
 static int temp;

 public static void main(String[] args) {

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

 public static void bubbleSort() {

  for (int i = 0; i < arr.length - 1; i++) {
   for (int y = 0; y < arr.length - i - 1; y++) {
    if (arr[y] > arr[y + 1]) {
     swap(y, y + 1);
     swapFlag[i] = true;
    }
   }
   System.out.println(i + " pass");
   if (i != 0) {
    if (swapFlag[i] == false && swapFlag[i - 1] == false) //condition where we are checking that int two succesive passes
     return;
   }
  }
 }

 public static void swap(int k, int r) {
  temp = arr[r];
  arr[r] = arr[k];
  arr[k] = temp;
 }

}

       
 

No comments:

Post a Comment