首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VB >

一个简单的算法,怎么写,才比较优化、简练?

2012-01-31 
一个简单的算法,如何写,才比较优化、简练??比如a2b11c7d14e3f9g10h11i18j13k10l10m11n17o16

一个简单的算法,如何写,才比较优化、简练??
比如 
a=2
b=11
c=7
d=14
e=3
f=9
g=10
h=11
i=18
j=13
k=10
l=10
m=11
n=17
o=16
p=19

按这个顺序排列的,然后找出第1个等于 10 的,答案是 g (k和l不算)

[解决办法]
这个算法还是算很简单的:

VB code
Sub Main()    Dim strValName$(15)    Dim arrData&(15)    Dim i&    For i = 0 To 15        strValName(i) = Chr$(97 + i)    Next    arrData(0) = 2    arrData(1) = 11    arrData(2) = 7    arrData(3) = 14    arrData(4) = 3    arrData(5) = 9    arrData(6) = 10    arrData(7) = 11    arrData(8) = 18    arrData(9) = 13    arrData(10) = 10    arrData(11) = 10    arrData(12) = 11    arrData(13) = 17    arrData(14) = 16    arrData(15) = 19    For i = 0 To 15        If (arrData(i) = 10) Then            MsgBox "第一个等于10的变量名称是:" & strValName(i), 64, "消息"            Exit For        End If    NextEnd Sub
[解决办法]
我用的是二分查找法
VB code
Private Sub Form_Load()    Dim arrNum(15) As Long    Dim a As Integer, b As Integer, c As Integer, d As Integer, e As Integer, f As Integer    Dim g As Integer, h As Integer, i As Integer, j As Integer, k As Integer, l As Integer    Dim m As Integer, n As Integer, o As Integer, p As Integer    Dim intResult As Integer    a = 2    b = 11    c = 7    d = 14    e = 3    f = 9    g = 10    h = 11    i = 18    j = 13    k = 10    l = 10    m = 11    n = 17    o = 16    p = 19    arrNum(0) = 2    arrNum(1) = 11    arrNum(2) = 7    arrNum(3) = 14    arrNum(4) = 3    arrNum(5) = 9    arrNum(6) = 10    arrNum(7) = 11    arrNum(8) = 18    arrNum(9) = 13    arrNum(10) = 10    arrNum(11) = 10    arrNum(12) = 11    arrNum(13) = 17    arrNum(14) = 16    arrNum(15) = 19        intResult = BinarySearch(arrNum(), 10)        If intResult <> -1 Then        MsgBox "第1个等于 10 的变量是" & Chr(97 + intResult)    End If    End Sub'二分查找法Private Function BinarySearch(ByRef arrNum() As Long, ByRef alngFind As Long) As Long    Dim intLeft As Integer, intRight As Integer, intMiddle As Integer        intLeft = LBound(arrNum())    intRight = UBound(arrNum())        While intLeft <= intRight            intMiddle = (intLeft + intRight) / 2        '        相同的数,则返回值        If arrNum(intMiddle) = alngFind Then           BinarySearch = intMiddle           Exit Function        End If                If arrNum(intMiddle) < alngFind Then            intLeft = intMiddle + 1        Else            intRight = intMiddle - 1        End If            Wend        If BinarySearch = 0 Then        BinarySearch = -1    End IfEnd Function 

热点排行