⑴设置区间信息为[2, 3], [15, 25], [10, 14], [1, 5], [30, 60], [15, 25];
⑵按区间左端点升序排序,得到区间信息为[1, 5], [2, 3], [10, 14], [15, 25], [15, 25], [30, 60], [15, 25];
⑶合并区间,得到[1, 5], [10, 25], [30, 60]。
说明:区间[1, 5]和[2, 3]合并为[1, 5],区间[10, 14]和[15, 25]合并为[10, 25],区间[10, 25]和[15, 25]合并为[10, 25],因此合并后的结果为[1, 5], [10, 25], [30, 60]三个区间。
程序功能如下:单击“读数据库”按钮Command1,程序从数据库读取数据,输出在文本框Text1中;单击“开始处理”按钮Command2,程序进行区间排序,并进行区间合并操作,操作后的结果输出在文本框Text2中。程序运行结果如图所示。
实现上述功能的VB程序如下,请回答下列问题:
Dim a(1 To 100) As Integer '数组a存储合并前的区间
Dim b(1 To 100) As Integer '数组b存储合并后的区间
Dim n As Integer 'n表示区间个数
Private Sub Command1_Click()
'读取数据库中的数据,存储到数组a中,并将区间个数存储在变量n中
'将区间信息输出在文本框Text1中,代码略
End Sub
Private Sub Command2_Click()
Dim s As String, i As Integer, j As Integer, k As Integer, t As Integer
For i = 1 To n - 1
For j = 1 To 2 * n - 2 * i Step 2
If Then
t = a(j): a(j) = a(j + 2): a(j + 2) = t
t = a(j + 1): a(j + 1) = a(j + 3): a(j + 3) = t
End If
Next j
Next i
b(1) = a(1): b(2) = a(2)
k = 2: i = 2: j = 3
Do While j <= 2 * n
If b(i) >= a(j) Then
If b(i) <= a(j + 1) Then
ElseIf b(i) + 1 = a(j) Then
b(k) = a(j + 1)
Else
k = k + 1:
k = k + 1: b(k) = a(j + 1)
i = i + 2
End If
j = j + 2
Loop
s = ""
For i = 1 To k - 2 Step 2
s = s & "[" & b(i) & "," & b(i + 1) & "]" & ","
Next i
s = s & "[" & b(i) & "," & b(i + 1) & "]"
Text2.Text = s
End Sub