本帖最后由 香川群子 于 2016-1-18 09:26 编辑
这样更好一些。
加入了<10时直接比较插入排序、提高速度效率。
另外,楼上代码在区间内不排序时排序范围有bug会造成死循环溢出堆栈、已经确认修改。
- Function QuickSort(tr, l&, u&, k1&, k2&, Optional z& = 0) 'A-Z
- Dim i&, j&, r, t
- ' cnt = cnt + 1
- If u - l < 10 Then
- For i = l + 1 To u
- r = tr(i)
- For j = i - 1 To l Step -1
- If tr(j) <= r Then Exit For Else tr(j + 1) = tr(j) '<= A-Z
- Next
- tr(j + 1) = r
- Next
- Else
- i = l: j = u: r = tr((l + u) \ 2)
- While i < j
- While tr(i) < r: i = i + 1: Wend '< A-Z
- While tr(j) > r: j = j - 1: Wend 'A-Z
- If i <= j Then t = tr(i): tr(i) = tr(j): tr(j) = t: i = i + 1: j = j - 1
- Wend
- ' Debug.Print tr(k1); tr(k2); l; j; i; u; cnt
- If z Then 'Sort [k1,k2]
- If l < j Then If k1 <= j Then Call QuickSort(tr, l, j, k1, k2, z)
- 'l,k1,j,k2/k1,l,k2,j/k1,l,j,k2/ Not l,j,k1,k2
- If i < u Then If i <= k2 Then Call QuickSort(tr, i, u, k1, k2, z)
- 'i,k1,u,k2/k1,i,k2,u/k1,i,u,k2/ Not k1,k2,i,u
- Else 'No Sort [k1,k2]
- If l < j Then If l < k1 Then If k1 <= j Then Call QuickSort(tr, l, j, k1, k2, z)
- 'l<k1,(k1<=j),(k2)
- If l < j Then If k1 < l Then If k2 < j Then Call QuickSort(tr, l, j, k1, k2, z)
- 'k1<l,(k2<j)
-
- If i < u Then If i < k1 Then If u <= k2 Then Call QuickSort(tr, i, u, k1, k2, z)
- '(i<k1),u<=k2
- If i < u Then If i < k2 Then If k2 < u Then Call QuickSort(tr, i, u, k1, k2, z)
- '(k1),(i<k2),k2<u
- End If
- End If
- If k1 = k2 Then QuickSort = tr(k1)
- End Function
复制代码 |