- Option Explicit
- Sub ptpx() '普通排序
- Dim arr, i%, j%, n%, gd, m1&, m2&, xx$, l&, u&
- 'arr = Array(5, 4, 2, 1, 5, 8, 7, 2, 7, 9, 3, 6) '正常随机顺序
- 'arr = Array(9, 8, 7, 7, 6, 5, 5, 4, 3, 2, 2, 1) '极端情况降序
- arr = Array(1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 9) '极端情况升序
- l = LBound(arr): u = UBound(arr): n = u - l + 1
- m1 = 0: m2 = 0
- For i = 0 To n - 2
- For j = i + 1 To n - 1
- m2 = m2 + 1 '记录比较次数
- If arr(j) < arr(i) Then
- gd = arr(j)
- arr(j) = arr(i)
- arr(i) = gd
- m1 = m1 + 1 '记录交换次数
- End If
- Next j
- Next i
- For i = 0 To n - 1
- xx = xx & arr(i) & ","
- Next i
- MsgBox "排序结果:" & Chr(10) & Left(xx, Len(xx) - 1) & Chr(10) _
- & "共比较" & m2 & "次,相当于数据个数" & n & "的" & Format(m2 / n, "0.0000") & "倍。" & Chr(10) _
- & "共交换" & m1 & "次,相当于数据个数" & n & "的" & Format(m1 / n, "0.0000") & "倍。", , "友情提示"
- End Sub
- Sub sheelpx() '希尔排序
- Dim arr, i%, j%, n%, gd, m1&, m2&, xx$, h&, l&, u&
- 'arr = Array(5, 4, 2, 1, 5, 8, 7, 2, 7, 9, 3, 6) '正常随机顺序
- 'arr = Array(9, 8, 7, 7, 6, 5, 5, 4, 3, 2, 2, 1) '极端情况降序
- arr = Array(1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 9) '极端情况升序
- l = LBound(arr): u = UBound(arr): n = u - l + 1
- m1 = 0: m2 = 0: h = n
- Do
- h = h \ 2
- For i = l + h To u
- gd = arr(i)
- For j = i - h To l Step -h
- m2 = m2 + 1 '记录比较次数
- If arr(j) > gd Then
- arr(j + h) = arr(j)
- m1 = m1 + 1 '记录交换次数
- Else
- Exit For
- End If
- Next j
- arr(j + h) = gd
- Next i
- Debug.Print h
- Loop Until h = 1
- For i = 0 To n - 1
- xx = xx & arr(i) & ","
- Next i
- MsgBox "排序结果:" & Chr(10) & Left(xx, Len(xx) - 1) & Chr(10) _
- & "共比较" & m2 & "次,相当于数据个数" & n & "的" & Format(m2 / n, "0.0000") & "倍。" & Chr(10) _
- & "共交换" & m1 & "次,相当于数据个数" & n & "的" & Format(m1 / n, "0.0000") & "倍。", , "友情提示"
- End Sub
复制代码 这是我参照写的对比测试代码。 |