16.小明學習了選擇排序后,對選擇排序算法進行了如下改進:在數(shù)組的所有元素中找出最小和最大數(shù)據(jù)的元素,然后將這兩個元素分別與第一個和最后一個元素交換數(shù) 據(jù),在余下的元素中找出最小和最大數(shù)據(jù)的元素,分別與第二個和倒數(shù)第二個元素交換數(shù)據(jù),以此類推,直到所有元素的數(shù)據(jù)按升序排列。程序運行界面如圖所示。 實現(xiàn)上述功能的VB程序如下,但加框處代碼有錯,請改正。 Const n=10 Dim a(1To n) As Integer Private Sub Command1_Click ( ) Dim left1As Integer,right1As Integer,Pmax As Integer,Pmin As Integer,t As Integer '隨機生成一組正整數(shù),存儲在數(shù)組a中,代碼略 left1=1:right1=n Do While left1<right1 Pmin=left1:Pmax=left1 For i=left1+1To ‘① If a(i)<a(Pmin) Then Pmin=i If a(i)>a(Pmax) Then Pmax=i Next i t=a(Pmin):a(Pmin)=a(left1):a(left1)=t If Pmax=left1Then ‘② t=a(Pmax):a(Pmax)=a(right1):a(right1)=t left1=left1+1 right1=right1-1 Loop '依次輸出排序后的數(shù)據(jù)。代碼略 End Sub
請在橫線處填入合適的代碼。 Const n=10 Dim a(1To n) As Integer 'Form_Load事件過程產(chǎn)生不重復的隨機整數(shù),按升序排序并在標簽Label1中顯示 Private Sub Form_Load( ) Dim i As Integer,j As Integer,temp As Integer Randomize For i=1To n a(i)=Int(Rnd*100)+1 For j=1To i-1 If a(i)=a(j) Then ①
Exit For‘退出For循環(huán) End If Next j Next i For i=2To n If a(i)<a(i-1)Then temp=a(i) For j=i-1To 1Step-1 If temp>a(j) Then Exit For a(j+1)=a(j) Next j ②
End If Next i For i=1To n Label1.Caption=Label1.Caption+Str(a(i))+““ Next i End Sub Private Sub Command1_Click( ?。?br />Dim i As Integer,j As Integer,m As Integer,k As Integer Dim key As Integer,flag As Boolean key=Val(Text1.Text) i=1:j=n flag=False Do While (i<=j) And (not flag) m=Int((i+j)/2) If a(m)=key Then flag=True If a(m)<key Then i=m+1Else j=m-1 Loop If flag=True Then For k=③
a(k)=a(k+1) Next k Label2.Caption=““ For k=1To n-1 Label2.Caption=Label2.Caption+Str(a(k))+““ Next k Else Label2.Caption=“該數(shù)沒有找到“ End If End Sub