摘要:
希尔排序(Shell Sort)是插入排序的一种。也称缩小增量排序,是直接插入排序算法的一种更高效的改进版本。希尔排序是非稳定排序算法。
目录:
- 基本思路
- Java实现
- Python实现
正文:
一. 基本思路
先取一个正整数d1小于n,把所有序号相隔d1的数组元素放一组,组内进行直接插入排序;然后取d2小于d1,重复上述分组和排序操作;直至di=1,即所有记录放进一个组中排序为止。
二. Java实现
package com.timen.daily_20161214;
public class Shell_Sort {
/**
* 希尔排序
* @param test_data
*/
private static void shell_sort(int[] test_data) {
System.out.print("\n希尔排序过程");
int d = test_data.length/2;
for (int i = d; i > 0; i /= 2) {
System.out.println("\n间隔为" + i);
for (int j = 0; j < i; j++) {
for (int k = j + i; k < test_data.length; k+=i) {
if (test_data[k] >= test_data[k-i]) {
int temp = test_data[k];
int index = k -i;
for (int l = index; l >= 0; l -= i) {
if (temp >= test_data[l]) {
test_data[l+i] = test_data[l];
index -= i;
}
}
test_data[index+i] = temp;
}
}
}
for (int k = 0; k < test_data.length; k++) {
System.out.print(test_data[k] + " ");
}
}
System.out.println("\n最终排序结果:");
for (int k = 0; k < test_data.length; k++) {
System.out.print(test_data[k] + " ");
}
}
public static void main(String[] args) {
System.out.println("排序前:");
int[] test_data = {1, 3, 6, 9, 12, 11, 15, 4, 2, 3, 8};
for (int i = 0; i < test_data.length; i++) {
System.out.print(test_data[i] + " ");
}
shell_sort(test_data);
}
}
运行结果:
排序前:
1 3 6 9 12 11 15 4 2 3 8
希尔排序过程
间隔为5
11 15 6 9 12 8 3 4 2 3 1
间隔为2
12 15 11 9 6 8 3 4 2 3 1
间隔为1
15 12 11 9 8 6 4 3 3 2 1
最终排序结果:
15 12 11 9 8 6 4 3 3 2 1
三. Python实现
# -*- coding: utf-8 -*-
def shell_sort(test_data):
print u"希尔排序过程"
step = len(test_data) / 2
while step >0:
for i in range(step):
index = i + step
while index < len(test_data):
if test_data[index] >= test_data[index - step]:
temp = test_data[index]
insert_index = index - step
while insert_index >= 0:
if temp >= test_data[insert_index]:
test_data[insert_index + step],test_data[insert_index] = test_data[insert_index], test_data[insert_index + step]
insert_index -= step
index += step
print step
step /= 2
print test_data
return test_data
if __name__ == '__main__':
a = [1, 3, 6, 9, 12, 11, 15, 4, 2, 3, 8]
print u"排序前:"
print a
b = shell_sort(a)
print u"最终排序结果:"
print b
运行结果:
D:\Python\python.exe D:/PythonProject/Timen_daily/daily_20161214.py
排序前:
[1, 3, 6, 9, 12, 11, 15, 4, 2, 3, 8]
希尔排序过程
5
[11, 15, 6, 9, 12, 8, 3, 4, 2, 3, 1]
2
[12, 15, 11, 9, 6, 8, 3, 4, 2, 3, 1]
1
[15, 12, 11, 9, 8, 6, 4, 3, 3, 2, 1]
最终排序结果:
[15, 12, 11, 9, 8, 6, 4, 3, 3, 2, 1]
Process finished with exit code 0
总结:
当n值较小时,n和n的2次方的差别也较小,即直接插入排序的最好时间复杂度O(n)和最坏时间复杂度0(n的2次方)差别不大。
参考文献:
百度百科-希尔排序