Algorithm Puzzles

3 comments:

  1. Please try this code

    package javalatte;

    import java.util.Arrays;

    public class InsertionSort {

    /**
    * @param args
    */

    private static int[] insertionSort(int[] array){

    for (int i =1; i < array.length; i++) {
    System.out.println("******************");
    for (int j = i; j > 0; j--) {
    boolean swapped = false;

    if( array[j-1] > array[j] ){
    int temp = array[j];
    array[j] = array[j-1];
    array[j-1] = temp;

    swapped = true;
    }
    if( ! swapped )
    break;

    System.out.println(Arrays.toString(array));
    }
    // System.out.println(Arrays.toString(array));
    }

    return array;
    }

    private static int[] insertionSortPradeep(int[] array){

    for (int i =1; i < array.length; i++) {
    System.out.println("******************");
    for (int j = 0; j < i; j++) {
    if( array[i] < array[j] ){
    int temp = array[j];
    array[j] = array[i];
    array[i] = temp;
    }
    System.out.println(Arrays.toString(array));
    }
    // System.out.println(Arrays.toString(array));
    }

    return array;
    }

    public static void main(String[] args) {

    int[] array = {2,5,3,1,8,4,6,9,7};
    // int[] array = {1,2,3,4,5,6,7,8,9};

    System.out.println("************ insertionSort *************");
    System.out.println("Before insertion sort..........");
    System.out.println(Arrays.toString(array));

    array = insertionSort( array );

    System.out.println("\nAfter insertion..........");
    System.out.println(Arrays.toString(array));


    /////////////////

    System.out.println("************ insertionSortPradeep *************");
    System.out.println("Before insertion sort..........");
    System.out.println(Arrays.toString(array));

    array = insertionSortPradeep( array );

    System.out.println("\nAfter insertion..........");
    System.out.println(Arrays.toString(array));



    } // main ends


    } // class ends


    ReplyDelete