Tuesday, June 19, 2012

Reverse Insert Sort

Problem -> Rewrite the INSERTION-SORT procedure to sort into non increasing instead of non decreasing order. Solution

package com.webspherenotes.algo;

public class InsertSortReverse {

  /**
   * @param args
   */
  public static void main(String[] args) {
    int[] input = { 1, 2, 3, 4, 5, 6, 7 };

    InsertSortReverse insertSort = new InsertSortReverse();
    insertSort.printArray(input);
    int[] ouptut = insertSort.sort(input);

    System.out.print("Result is ->");
    insertSort.printArray(ouptut);
    System.out.println("Number of exchagnes " + insertSort.noOfExchanges);

  }

  private int[] sort(int[] input) {
    int length = input.length;
    for (int counter = length - 2; counter >= 0; counter--) {

      int key = input[counter];
      int exchangeCounter = counter + 1;
      while (exchangeCounter < length && key < input[exchangeCounter]) {
        exchange(input, exchangeCounter - 1, exchangeCounter);
        exchangeCounter++;
        printArray(input);
      }
    }

    return input;
  }

  private void printArray(int[] input) {

    System.out.print("{");
    for (int i = 0; i < input.length; i++) {
      System.out.print(input[i]);
      if (i != input.length - 1)
        System.out.print(" , ");
    }
    System.out.println("}");
  }

  int noOfExchanges;

  private void exchange(int[] array, int first, int second) {
    int temp = array[first];
    array[first] = array[second];
    array[second] = temp;
    noOfExchanges++;
  }
}

No comments:

Post a Comment