'希尔排序
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
VB排序算法-希尔排序
博客主要展示了希尔排序算法的代码实现。通过定义跨度、读取元素数量等步骤,对数组进行排序,可根据参数选择升序或降序排序。代码中包含了跨度的计算、元素的比较与交换等操作,实现了希尔排序的核心逻辑。
3391





