1、算法說明數(shù)組中元素的插入和刪除一般是在已固定序列的數(shù)組中插入或刪除一個元素,使得插入或刪除操作后的數(shù)組還是有序的。
基本思路:首先要找到插入位置或要刪除的元素。
1) 插入
代碼如下:
Private Sub Command1_Click()
Dim a(10) As Integer
Dim i As Integer, k As Integer
For i = 0 To 9 '生成數(shù)組
a(i) = i * 3 + 1
Print a(i);
Next i
Print
Print "插入14"
For k = 0 To 9 '查找插入14在數(shù)組中的位置
If 14 < a(k) Then Exit For
Next k
For i = 9 To k Step -1 '從最后元素開始逐個后移,騰出位置
a(i + 1) = a(i)
Next i
a(k) = 14 '插入數(shù)14
For i = 0 To 10
Print a(i);
Next i
Print
End Sub
2) 1 4 7 10 13 16 19 22 25 28
K
刪除 代碼如下:
Dim a() as integer
….
ReDim a(1 to n)
…
For i=k+1 to n
a(i-1)=a(i)
Next I
Redim preserve a(1 to n-1)
2、實戰(zhàn)練習 1) 補充代碼(2001秋二(8))
C盤根目錄下文件Data4.txt的內(nèi)容是:2,4,6,8,10,1,3,5,7,9。下面程序的功能是將文件后半部分的奇數(shù)分別按序插入到前半部分的適當位置,得到的新數(shù)列是:1 2 3 4 5 6 7 8 9 10。(實現(xiàn)方法:第一次調(diào)整后的數(shù)列是:1 2 4 6 8 10 3 5 7 9第二次調(diào)整后的數(shù)列是:1 2 3 4 6 8 10 5 7 9)。
Option Explict
Private Sub Form_Click()
Dim A(10) As Integer,i As Integer,J As Integer
Open "c:\Data4.txt" For Input As #12
Do (1)
J=J+1
Input #12,A(J)
Loop
Call Insert(A)
For i=1 To 10
Print A(i);
Next i
Print
Close #12
End Sub
Private Sub Insert(A() As Integer)
Dim i As Integer,Putp As Integer,J As Integer
Dim Getp As Integer,N As Integer,Tem As Integer
N=UBound(A)/2
Putp=1
Getp=N+1
For i=1 To N
Tem=A(Getp)
For J=Getp To Putp +1 Step -1
(2)
Next J
A(Putp)=Tem
Getp=Getp+1
Putp= (3)
Next i
End Sub
2) 補充代碼(2001春二(8))
下面程序得功能是將無序數(shù)組中相同得數(shù)只保留一個,其余得刪除,并輸出經(jīng)過刪除后的數(shù)組元素,刪除相同數(shù)是通過將該數(shù)組元素后面的元素在數(shù)組內(nèi)依次前移替換前一個元素的值實現(xiàn)的。數(shù)組各元素的值從文件data.txt中讀取。
Option Explict
Option Base 1
Private Sub Form_Click()
Dim I As Integer,J As Integer,K As Integer
Dim A()As Integer,T As Integer,M As Integer
Open "c:\my documents\2000test\data.txt" For Input As #1
Do While (1)
I=I+1
Redim Preserve A(I)
Input #1,A(I)
Loop
M=1:T= (2)
Do While M<T
I=M+1
Do While I<=T
If A(I)=A(M)Then
For J=1 To (3)
A(J)=A(J+1)
Next J
T=T-1
Else
I= (4)
End If
Loop
M=M+1
Loop
Redim Preserve A(T)
For I=1 To T
Print A(I);
Next I
Print
End Sub
北京 | 天津 | 上海 | 江蘇 | 山東 |
安徽 | 浙江 | 江西 | 福建 | 深圳 |
廣東 | 河北 | 湖南 | 廣西 | 河南 |
海南 | 湖北 | 四川 | 重慶 | 云南 |
貴州 | 西藏 | 新疆 | 陜西 | 山西 |
寧夏 | 甘肅 | 青海 | 遼寧 | 吉林 |
黑龍江 | 內(nèi)蒙古 |