Java : Insertion Sort

/**
 * Created on 25-Jun-18 3:32 PM.
 *
 * @author Aayush
 */
public class InsertionSort {

  public static void sort(int[] array){
    for(int i=1; i<array.length; i++){
      moveToAppropriatePlace(array, i);
    }
  }

  /**
   * Pick a value at index @indexOfCurrentValue, and shift it backwards finding the appropriate place
   *
   * @param array
   * @param indexOfCurrentValue
   */
  private static void moveToAppropriatePlace(int[] array, int indexOfCurrentValue) {
    int currentValue = array[indexOfCurrentValue];
    int i = indexOfCurrentValue;
    while(i>0){
      if(array[i-1] > currentValue) array[i] = array[i-1];
      else break;
      i--;
    }
    if(i != indexOfCurrentValue) array[i] = currentValue;
  }
}

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

-Aayush Shrivastava


Are you satisfied?

Leave a comment