现在的位置: 首页 > 综合 > 正文

快速排序算法 vb示例及分析

2012年07月14日 ⁄ 综合 ⁄ 共 1855字 ⁄ 字号 评论关闭

快速排序对冒泡排序的一种改进。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。

 

'快速排序算法,对字符串数组进行排序
Private Sub quicksort(ByRef arrValue() As String, ByVal intLx As Integer, ByVal intRx As Integer)
    'arrValue()是待排的数组,intLx,intRx为左右边界
    Dim strValue    As String
    Dim I           As Integer
    Dim j           As Integer
    Dim intLoop     As Integer
   
    I = intLx
    j = intRx
    Do
        While arrValue(I) <= arrValue(j) And I < j: I = I + 1: Wend
        If I < j Then
            strValue = arrValue(I)
            arrValue(I) = arrValue(j)
            arrValue(j) = strValue
           
           
            strValue = "1: i=" & CStr(I) & " j=" & CStr(j) & " "
            For intLoop = 0 To UBound(arrValue)
                strValue = strValue & " " & arrValue(intLoop)
            Next
            Debug.Print strValue
        End If
        While arrValue(I) <= arrValue(j) And I < j: j = j - 1: Wend
        If I < j Then
            strValue = arrValue(I)
            arrValue(I) = arrValue(j)
            arrValue(j) = strValue
           
            strValue = "2: i=" & CStr(I) & " j=" & CStr(j) & " "
            For intLoop = 0 To UBound(arrValue)
                strValue = strValue & " " & arrValue(intLoop)
            Next
            Debug.Print strValue

        End If
    Loop Until I = j
    I = I - 1: j = j + 1
   
    Debug.Print vbCrLf

    If I > intLx Then
        Call quicksort(arrValue, intLx, I)
    End If
    If j < intRx Then
        Call quicksort(arrValue, j, intRx)
    End If
End Sub

Private Sub Form_Load()
    Dim arr(8) As String
   
    arr(0) = "r"
    arr(1) = "e"
    arr(2) = "a"
    arr(3) = "n"
    arr(4) = "b"
    arr(5) = "u"
    arr(6) = "c"
    arr(7) = "o"
    arr(8) = "f"
   
    Call quicksort(arr, 0, UBound(arr))
End Sub

快速排序过程中的数据变化列表如下所示。从中可以看到一共执行了5次递归方法。每次执行时都是通过循环将数组从中间分割成2半,大的在右边,小的在左边,然后再针对这2半分别调用下一次递归方法。

排序前:      r e a n b u c o f

1: i=0 j=8  f e a n b u c o r
2: i=0 j=6  c e a n b u f o r
1: i=3 j=6  c e a f b u n o r
2: i=3 j=4  c e a b f u n o r

1: i=0 j=3  b e a c f u n o r
2: i=0 j=2  a e b c f u n o r
1: i=1 j=2  a b e c f u n o r

1: i=2 j=3  a b c e f u n o r

1: i=5 j=8  a b c e f r n o u
2: i=5 j=7  a b c e f o n r u

1: i=5 j=6  a b c e f n o r u

 

抱歉!评论已关闭.