Java : Bubble Sort

/**
 * Created on 25-Jun-18 12:34 PM.
 *
 * @author Aayush
 */
public class BubbleSort {
  public static void sort(int[] array){
    for(int i=array.length-1; i>=0; i--) {
      if(!moveHighestValueToEnd(array, i))
        break;
    }
  }

  /**
   * Moves the highest value to @endIndex in the array
   *
   * @param array
   * @param endIndex
   * @return
   */
  private static boolean moveHighestValueToEnd(int[] array, int endIndex){
    boolean flag = false;
    for(int i = 0; i < endIndex; i++){
      if(array[i] > array[i+1]) {
        int temp = array[i];
        array[i] = array[i+1];
        array[i+1] = temp;
        flag = true;
      }
    }
    return flag;
  }
}

That’s All. P)
Happy Java-ing.

-Aayush Shrivastava


Are you satisfied?

Leave a comment