import java.util.Random;
public class Sort {
//生成随机数数组
public void init( int[] data ) {
Random rand = new Random();
for ( int i=0; i<data.length; i++ ) {
data[i] = rand.nextInt(100);
}
printRawData( data );
}
//打印原始数据
private void printRawData( int[] data ) {
System.out.println( "\nraw data(len=" + data.length + "):" );
for ( int i=0; i<data.length; i++ ) {
System.out.print( data[i] + " " );
}
System.out.println();
}
//打印排序结果
private void printResultData( String sort, int[] result ) {
System.out.println( sort + " result(len=" + result.length + "):" );
for ( int i=0; i<result.length; i++ ) {
System.out.print( result[i] + " " );
}
System.out.println();
}
//希尔排序
public void shellSort( int[] data ) {
int i=0, j = 0;
int temp = 0;
int gap = data.length;
do {
gap = gap/3 + 1;
System.out.println( "gap=" + gap );
for ( i=gap; i<data.length; i++ ) {
temp = data[i];
for( j=i; (j>=gap) && temp<data[j-gap]; j-=gap ) {
data[j] = data[j-gap];
}
data[j] = temp;
}
} while ( gap > 1 );
printResultData( "shellSort", data );
}
public static void main ( String[] args ) {
Sort sort = new Sort();
int[] a = new int[9];
sort.init( a );
sort.shellSort( a );
}
}
希尔排序(Java实现)
最新推荐文章于 2020-02-06 13:48:08 发布