Monday, September 15, 2014

Shell Sort Implementation [Java]

This program implements the Shell Sort Algorithm.

Shellsort, also known as Shell sort or Shell's method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). The method starts by sorting elements far apart from each other and progressively reducing the gap between them. Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange.

Code:

import java.util.Arrays;

public class ShellSortILimit { 
    
    public static void shellSort(int[] a) {
        int factor = a.length / 2;
        while (factor != 0) {
            insertionSort(a, factor);
            System.out.println("Factor " + factor + " processed: " + Arrays.toString(a));
            factor /= 2;
        }
    }

    private static void insertionSort(int[] a, int factor) {
        for(int i=0, j=factor;j<a.length;++i, ++j){
            int tempI = i, tempJ = j;
            System.out.println(i+" "+j);
            while(a[tempJ]<a[tempI]){
                /*
                Integer class is immutable. So you can't
                make a function like 
                void swap(Integer a, Integer b){} 
                to swap values. You have to do it manually.
                */
                int temp = a[tempI]; 
                a[tempI] = a[tempJ];
                a[tempJ] = temp;
                tempI--; tempJ--; 
                if(tempI == -1) break;
            } 
        }
    }

    public static void main(String[] args) {
        int test[] = new int[]{0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
        shellSort(test);
        System.out.println(Arrays.toString(test)); 
    }
}

Output:

0 5
1 6
2 7
3 8
4 9
5 10
Factor 5 processed: [0, 4, 3, 2, 1, 0, 9, 8, 7, 6, 5]
0 2
1 3
2 4
3 5
4 6
5 7
6 8
7 9
8 10
Factor 2 processed: [0, 2, 1, 0, 3, 4, 7, 6, 5, 8, 9]
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
Factor 1 processed: [0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

No comments:

Post a Comment