VFB实现快速排序

网上查询了快速排序的例子,修改为FB版本,记录如下:

'// 参数说明:
'// a -- 待排序的数组
'// l -- 数组的左边界(例如,从起始位置开始排序,则l=0)
'// r -- 数组的右边界(例如,排序截止到数组末尾,则r=a.length-1)
Sub QuickSort(ByVal a As Long Ptr ,ByVal l As Long ,ByVal r As Long) 
    If l < r Then
        Dim i As Long ,j As Long ,x As Long
        i = l
        j = r
        x = a[i]
        While i < j
            While (i < j AndAlso a[j] > x)
                j -= 1 '// 从右向左找第一个小于x的数 
            Wend
            If i < j Then
                a[i] = a[j]   '// 将小于x的值放在左边
                i += 1 
            End If
            While i < j AndAlso a[i] < x
                i += 1    '// 从左向右找第一个大于x的数
            Wend  
            if i < j then
                a[j] = a[i]
                j -= 1   '// 将大于x的值放在右边
            End If 
        Wend
        a[i] = x
        QuickSort(a ,l ,i - 1)
        QuickSort(a, i + 1, r)
    End If
End Sub

'调用
Sub Form1_Command1_BN_Clicked(hWndForm As hWnd, hWndControl As hWnd)  '单击
    Dim arr(...) As Long = {9 ,5 ,1 ,6 ,2 ,3 ,0 ,4 ,8 ,7}
    Print "排序前:"
    For i As Long = 0 To 9
        Print arr(i),
    Next
    Print 
    QuickSort(@arr(0) ,0 ,9)
    Print "排序后:"
    For i As Long = 0 To 9
        Print arr(i),
    Next
    Print 
End Sub

VFB实现快速排序_第1张图片

 

你可能感兴趣的:(FreeBASIC随记,算法,数据结构)