zhaochunqi
5/7/2014 - 12:40 PM

Shell排序

Shell排序

import java.util.*;

public class TestShellSort {
	public static void main(String[] args) {
		Integer[] intarray = {10,2,4,243,42,34,2,42,4,24,4,5,56,657,68,7,988,9,80,5};
		System.out.println("Origin :"+Arrays.toString(intarray));
		shellsort(intarray);
		System.out.println("After  :"+Arrays.toString(intarray));
	}

	public static void shellsort(Comparable[] a) {
		int N = a.length;
		int h = 1;
		while(h < N) {
			h = 3*h + 1;
		}
		while(h>=1){
			for(int i=h;i<N;i++) {
				for(int j=i;j >= h && less(a[j],a[j-h]);j=j-h) {
					exch(a,j,j-h);
				}
			}
			h = h/3;
		}
	}

	public static Boolean less(Comparable v,Comparable w) {
		return v.compareTo(w) < 0;
	}

	public static void exch(Comparable[] a,int m,int n) {
		Comparable c = a[m];
		a[m] = a[n];
		a[n] = c;
	}
}