注意while(h>0) 循环的使用.那位高手能告诉我下,为什么把这个循环去掉,为什么就有问题了呢?而我认为应该出现死循环才对啊? 但是没有出现。有兴趣的朋友,欢迎讨论
package high;
public class HighSort {
private int[] a; //待排序的数组
public int elems; //数据的长度,不是数组的长度
private int maxSize;
/*
* 初始化
*/
public HighSort( int max){
maxSize = max;
a = new int[maxSize];
elems =0;
}
public void add( int i){
if(elems==maxSize){
return;
}
a[elems] = i;
elems ++;
}
public void display(){
for( int i=0;i<elems;i++){
System.out.print(a[i]+ " ");
}
System.out.println();
}
// 注意传值调用陷阱
public void swap( int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public void shellSort(){
int h =1;
while(h <= elems/3){
h = h*3+1;
}
while(h>0){
for( int out=h;out<elems;out++){
int temp = a[out];
int in = out;
while(in>h-1 && a[in-h]>=temp){
swap(in -h,in);
in = in -h;
}
a[in] =temp;
}
h =(h -1)/3;
}}
public static void main(String[] args) {
HighSort array = new HighSort(10);
array.add(12);
array.add(10);
array.add(3);
array.add(4);
array.add(11);
array.add(8);
array.add(54);
array.add(7);
array.add(4);
array.display();
array.shellSort();
array.display();
}
}
public class HighSort {
private int[] a; //待排序的数组
public int elems; //数据的长度,不是数组的长度
private int maxSize;
/*
* 初始化
*/
public HighSort( int max){
maxSize = max;
a = new int[maxSize];
elems =0;
}
public void add( int i){
if(elems==maxSize){
return;
}
a[elems] = i;
elems ++;
}
public void display(){
for( int i=0;i<elems;i++){
System.out.print(a[i]+ " ");
}
System.out.println();
}
// 注意传值调用陷阱
public void swap( int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public void shellSort(){
int h =1;
while(h <= elems/3){
h = h*3+1;
}
while(h>0){
for( int out=h;out<elems;out++){
int temp = a[out];
int in = out;
while(in>h-1 && a[in-h]>=temp){
swap(in -h,in);
in = in -h;
}
a[in] =temp;
}
h =(h -1)/3;
}}
public static void main(String[] args) {
HighSort array = new HighSort(10);
array.add(12);
array.add(10);
array.add(3);
array.add(4);
array.add(11);
array.add(8);
array.add(54);
array.add(7);
array.add(4);
array.display();
array.shellSort();
array.display();
}
}
本文转自 randy_shandong 51CTO博客,原文链接:http://blog.51cto.com/dba10g/237034,如需转载请自行联系原作者