Friday, June 29, 2012

Selection Sort in Java



import java.util.Comparator;

public class SelectionSort {
      /**
       * This method will sort the int type array in ascending order
       * @param array
       */
      public static void selectionSort(int[] a) {
            int length = a.length - 1;
            for (int x = 0; x < length; x++) {
                  int min = x;
                  for (int y = x + 1; y <= length; y++) {
                        if (a[y] < a[min]) {
                              min = y;
                        }
                  }
                  int tmp = a[x];
                  a[x] = a[min];
                  a[min] = tmp;
            }
      }
      /**
       * 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 selectionSort(T[] a) {
            int length = a.length - 1;
            for (int x = 0; x < length; x++) {
                  int min = x;
                  for (int y = x + 1; y <= length; y++) {
                        if (a[y].compareTo(a[min]) < 0) {
                              min = y;
                        }
                  }
                  T tmp = a[x];
                  a[x] = a[min];
                  a[min] = tmp;
            }
      }
      /**
       * 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[] a, Comparator<T> c) {
            int length = a.length - 1;
            for (int x = 0; x < length; x++) {
                  int min = x;
                  for (int y = x + 1; y <= length; y++) {
                        if (c.compare(a[y], a[min]) < 0) {
                              min = y;
                        }
                  }
                  T tmp = a[x];
                  a[x] = a[min];
                  a[min] = tmp;
            }
      }
}

No comments:

Post a Comment