Algorithms

February 3, 2009

Insertion sort algorithm

Filed under: Algorithm implementation, Uncategorized — Tags: , , , — vinu76jsr @ 9:15 pm

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package algorithmsx;

/**
 *
 * @author ramakant
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int array[] = new int[10];

        //filling arry with random numbers between 1 and 100
        for (int i = 0; i < 10; i++) {
            array[i]=(int)(Math.random()*100)+1;
        }
        insertionSort(array);
    }

    static void insertionSort(int []ar){
        int key;
        int len = ar.length;
        for(int i=1;i<len;i++){
            key=ar[i];
            for (int j = i-1; j >= 0; j--) {
                if(key<ar[j])
                    ar[j+1]=ar[j];
                else{
                    ar[j+1]= key;
                    break;
                }
            }
        }
        for (int i : ar) {
            System.out.println(i);
        }

    }

}


this is the implementation of insertion sort in java, the program was developed with Netbeans IDE 6.5
Reblog this post [with Zemanta]

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.