希尔排序实现原理:
选定一个增长量h,按照增长量 h 作为数据分组的依据,对数据进行分组;对分好组的每一组数据完成插入排序;减小增长量,最小减为 1,重复第二步操作。如图,颜色相同的进行比较:
希尔排序算法实现:(不稳定排序)
public static void main(String
[] args
) {
int[] arr
= {9, 1, 2, 5, 7, 4, 8, 6, 3, 5};
sort(arr
);
for (int i
: arr
) {
System
.out
.print(i
+"\t");
}
}
public static void sort(int[] a
) {
int h
= 1;
while (h
< a
.length
/ 2) {
h
= 2 * h
+ 1;
}
while (h
>= 1) {
for (int i
= h
; i
< a
.length
; i
++) {
for (int j
= i
; j
>= h
; j
-= h
) {
if (greater(a
[j
- h
], a
[j
])) {
exc(a
, j
- h
, j
);
} else {
break;
}
}
}
h
/= 2;
}
}
public static boolean greater(int v
, int w
) {
return v
> w
;
}
public static void exc(int[] a
, int i
, int j
) {
int temp
;
temp
= a
[i
];
a
[i
] = a
[j
];
a
[j
] = temp
;
}
程序执行结果:
转载请注明原文地址:https://blackberry.8miu.com/read-34783.html