Friday, June 29, 2012

Insertion Sort in Java


import java.util.Comparator;

public class InsertionSort {
     
      /**
       * This method will sort the int type array in ascending order
       * @param array
       */
      public static void insertionSort(int array[]) {
            int n = array.length;
            for (int i = 1; i < n; i++) {
                  int j = i;
                  int value = array[i];
                  while ((j > 0) && (array[j - 1] > value)) {
                        array[j] = array[j - 1];
                        j--;       
                  }
                  array[j] = value;
            }
      }
      /**
       * This method will sorts the array of object in ascending order which implements Comparable.
       * like String, Byte, Short, Integer, Long, Float, Double, Character,
       * Boolean, BigInteger, BigDecimal
       * @param <T>
       * @param array
       */
      public static <T extends Comparable<T>> void insertionSort(T[] array) {
            int n = array.length;
            for (int i = 1; i < n; i++) {
                  int j = i;
                  T value = array[i];
                  while ((j > 0) && (array[j-1].compareTo(value)>0)) {
                        array[j] = array[j - 1];
                        j--;       
                  }
                  array[j] = value;
            }
      }
     
      /**
       * This method will sorts the array of objects based on provided comparator in ascending order.
       * @param <T>
       * @param array
       */
      public static <T> void selectionSort(T[] array, Comparator<T> comparator) {
            int n = array.length;
            for (int i = 1; i < n; i++) {
                  int j = i;
                  T value = array[i];
                  while ((j > 0) && (comparator.compare(array[j-1], value)>0)) {
                        array[j] = array[j - 1];
                        j--;       
                  }
                  array[j] = value;
            }
      }
}

No comments:

Post a Comment