Java program – Insertion sort

by Nideesh C on April 29, 2011 · 0 comments

in Java Programming




// suppress unchecked warnings in Java 1.5.0_6 and later
@SuppressWarnings("unchecked")

public class Insertion {

    public static void sort(Comparable[] a) {
        int N = a.length;
        for (int i = 1; i < N; i++) {
            for (int j = i; j > 0; j--) {
                if (a[j-1].compareTo(a[j]) > 0) {
                    exch(a, j-1, j);
                }
                else break;
            }
        }
    }

    // exchange a[i] and a[j]
    private static void exch(Comparable[] a, int i, int j) {
        Comparable swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }

    // read in a sequence of words from standard input and print
    // them out in sorted order
    public static void main(String[] args) {
        String[] a = StdIn.readAll().split("\\s+");
        sort(a);
        for (int i = 0; i < a.length; i++) {
            StdOut.print(a[i] + " ");
        }
        StdOut.println();
    }
}


/*************************************************************************
 *  Execution:    java Insertion < input.txt
 *
 *  Reads in strings from standard input and prints them in sorted order.
 *  Uses insertion sort.
 *
 *************************************************************************/



Not Satisfied ? Just search & get the result

Related Posts Plugin for WordPress, Blogger...
Be Sociable, Share!

Related posts:

  1. Java program – Array I/O library
  2. C++ program to implement Insertion sort using class
  3. Java program – A simple filter
  4. C program to sort given N elements using SELECTION sort method using functions a) To find maximum of elements b) To swap two elements
  5. Java program – Percolation scaffolding

Leave a Comment

Previous post:

Next post: