/**
* shell排序很简单,核心依然是两两交换,只不过交换的次序有所改变。
* shell排序会设置一个增量,其实就是一个长度值,第一个长度值取整体长度的一半(向上取整)。假如第一个长度取为5;
* 然后两辆比较,source[0]跟source[5]比大小,souce[1]跟source[6]比大小 ...根据大小数值进行交换。
* 第一次比完以后再取长度的一半,5的一半为3,然后再按上述步骤进行比较;以此类推;
* 增量取值分别为:5,3,2,1.增量长度为1时,排序就完成了。
* @author 王嘉锐
*
*/
public class ShellSort {
public static void shellSort(int[] source){
int dataLength = (int)Math.ceil((double)source.length/2); // 第一次分割的长度
int index = 0; //需要交换的值的位置,从第一次分割的长度开始
int swapIndex;//需要交换的值的位置,从0开始
int flag = 1; //设立一个标记,用于一会退出循环
while(dataLength != 0 ){
index = dataLength;
//此处进行排序
while(index < source.length){
swapIndex = index -dataLength;
if(source[swapIndex] > source[index]){
swap(source, swapIndex, index);
}
index++;
}
//跳出循环
if(flag == -1){
break;
}
dataLength = (int)Math.ceil((double)dataLength/2);
//当dataLength等于1时,即增量为1时,设立标记为-1,目的是让上述循环做最后一次驯韩
if(dataLength == 1){
flag = -1;
}
}
}
//交换数值
public static void swap(int[] source, int x, int y){
int temp = source[x];
source[x] = source[y];
source[y] = temp;
}
public static void main(String[] args) {
int[] a = {5,1,2,0,2,45,342,63,78};
shellSort(a);
for(int i = 0; i < a.length; i++){
System.out.println(a[i]);
}
}
}
shell排序
最新推荐文章于 2024-08-04 11:07:52 发布