Monday, September 15, 2014

Insertion Sort - Implementation [Java]

The insertion sort is really very easy. I thought of practicing it before implementing the Shell Sort.

Code:

import java.util.Arrays;

public class InsertionSort {
    public static void  insertionSort(int[] a){
        for(int i=1;i<a.length;++i){
            int j = i;
            while(a[j]<a[j-1]){
                int temp = a[j];
                a[j] = a[j-1];
                a[j-1] = temp; 
                if(--j==0)break;
            }
        }
    }
    public static void main(String[] args){
        int test[] = {4, 3, 1, 2, 1};
        insertionSort(test);
        System.out.println(Arrays.toString(test));
    }
}

Output:

[1, 1, 2, 3, 4]

No comments:

Post a Comment