'希尔排序
Sub ShellSort0(MyArray(), Optional ByVal SortByDesc As Boolean)
Dim Distance
Dim size
Dim Index
Dim NextElement
Dim temp
'读取元素的数量
size = UBound(MyArray) - LBound(MyArray) + 1
'定义当前跨度
Distance = 1
'将跨度定义为小于元素的数量的2的最大幂
While (Distance <= size)
Distance = 2 * Distance
Wend
'再找出跨度的中点
Distance = (Distance / 2) - 1
While (Distance > 0)
'读取中点的下标
NextElement = LBound(MyArray) + Distance
'移排序并移动中点(不大于最大下标)
While (NextElement <= UBound(MyArray))
'将中点作为当前下标
Index = NextElement
Do
'中点在跨度后面则要处理
If Index >= (LBound(MyArray) + Distance) Then
'根据是升序或降序进行分别处理
If SortByDesc = False Then
'升序:如果当前值小于上一个值,则互换
If MyArray(Index) < MyArray(Index - Distance) Then
temp = MyArray(Index)
MyArray(Index) = MyArray(Index - Distance)
MyArray(Index - Distance) = temp
Index = Index - Distance
Else
Exit Do
End If
ElseIf SortByDesc = True Then
'降序:如果当前值大于上一个值,则互换
If MyArray(Index) > MyArray(Index - Distance) Then
temp = MyArray(Index)
MyArray(Index) = MyArray(Index - Distance)
MyArray(Index - Distance) = temp
Index = Index - Distance
Else
Exit Do
End If
End If
Else
Exit Do
End If
Loop
NextElement = NextElement + 1
Wend
Distance = (Distance - 1) / 2
Wend
End Sub
03-15
1212
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-23
2182
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)