将数组a和数组b合并为升序排列的数组c,并将其显示在label3中
2,单击“合并”按钮后,将数组a和数组b合并为升序排列的数组c,并将其显示在label3中
要求1:程序应可以处理可变长度的数据。
要求2:合并的同时,保持c中数据始终有序 展开
这是一个比较“浩大”的工程呀!
1、既然“要求1:程序应可以处理可变长度的数据。”,那就说明数组a和b的数据时如如进来的。
我这里就临时放置了两个文本框控件,存储原始文本。
2、合并的同时保持C有序,这里采用了ReDim Preserve控制才的容量和原有数据。
3、为了验证C合并过程中有序,我加了一段程序。应用时删去即可。
具体代码如下(同时将程序上传,可以下载附件直接应用):
Dim a() As Integer, b() As Integer, c() As Integer
Private Sub Command1_Click()
Dim i As Integer, j As Integer, k As Integer, n As Integer, tmp As Integer
n = UBound(a)
ReDim c(n)
'首先将数组a全部Copy到c
For i = 0 To UBound(a)
c(i) = a(i)
Next
'将数组b逐个插入到c,保持C有序
Dim str As String, m As Integer '临时变量用于测试程序
For i = 0 To UBound(b)
For j = 0 To n
If b(i) < c(j) Then Exit For
Next
n = n + 1
ReDim Preserve c(n)
For k = n - 1 To j Step -1
c(k + 1) = c(k)
Next
c(j) = b(i)
'临时变量用于测试程序
'============================
str = ""
For m = 0 To UBound(c)
str = str & CStr(c(m)) & ","
Next
Debug.Print Left(str, Len(str) - 1)
'========================================
Next
End Sub
Private Sub Form_Load()
'准备数组a、b的内容
' Text1.Text = "11,25,56,67,77,98"
' Text2.Text = "8,33,56,83"
Text1.Text = "11,98,25,56,67,77"
Text2.Text = "8,56,33,83"
Dim i As Integer
Dim var As Variant
var = Split(Text1.Text, ",")
ReDim a(UBound(var))
For i = 0 To UBound(var)
a(i) = var(i)
Next
var = Split(Text2.Text, ",")
ReDim b(UBound(var))
For i = 0 To UBound(var)
b(i) = var(i)
Next
'对数组a、b排序
sort a()
sort b()
'将数组a、b分别放入Label1、Label2
Dim str As String
For i = 0 To UBound(a)
str = str & CStr(a(i)) & ","
Next
Label1.Caption = Left(str, Len(str) - 1)
str = ""
For i = 0 To UBound(b)
str = str & CStr(b(i)) & ","
Next
Label2.Caption = Left(str, Len(str) - 1)
End Sub
Function sort(a() As Integer)
Dim i As Integer, j As Integer, tmp As Integer
For i = 0 To UBound(a) - 1
For j = i + 1 To UBound(a)
If a(i) > a(j) Then
tmp = a(i)
a(i) = a(j)
a(j) = tmp
End If
Next
Next
End Function
你比答案给的的还难。。。如果我拿到这题怎么可能写出这么复杂的来。。。
你忽略掉多余的部分就可以了。
吃蛋糕的时候怪罪做蛋糕的人顺便送了一个火腿。
哈哈!