public class Test {
public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 };
public static void main(String args[]) {
System.out.print("排序前: ");
for (int i = 0; i < a.length; i++)
System.out.print("\t" + a[i]);
System.out.println();// 换行
shellSort(); // 希尔排序
System.out.print("排序后: ");
for (int i = 0; i < a.length; i++)
System.out.print("\t" + a[i]);
}
/**
* 希尔排序算法思想:这是一种优化了的插入法排序,针对较极端的情况下每次插入新数据需要移动大量原有数据的情况。
* 这种方法采用一个分组间距d(array.length>d>0)把原有数组分成若干个小数组,新数组内分别应用插入法排序。
* 然后缩小d的取值重新排序,直到d=1所有数据完成排序。算法效率与分组间距d的取值有很大关系,可查阅相关网络资料。
* 较常规的做法是d取初始值array.length/2,每次完成排序d/=2,直到d=1。
*/
public static void shellSort() {
int groupLength = a.length;// 分组间距初始化
while ((groupLength /= 2) > 0) {// 此循环区分分组间距的变化,即每次开始新的循环意味着分组间距发生了变化
for (int i = groupLength; i < a.length; i ++) {// 此循环增加数组中元素的个数,即每次开始新的循环意味着在有序数组上增加一个新的元素
int temp = a[i];
int j;
for (j = i - groupLength; j >= 0; j -= groupLength) {// 此循环寻找新元素在有序数组中的位置
if (temp < a[j])
a[j + groupLength] = a[j];
else
break;
}
a[j + groupLength] = temp;
}
}
}
}
希尔排序学习心得
最新推荐文章于 2024-01-09 13:13:35 发布