这是一个字符串
我不明白如何制作矩阵并调用它VBScript,没有退出虽然你不能打破While循环,除非你使用语法Do While ... Loop和Exit Do.此外,VBScript(至少Microsoft WSH)不使用任何布尔电路优化,所以如果你写,而j> 0和arr(j-1)> x这将导致尝试访问arr(-1)的错误,该错误超出了有效的子范围。
Option Explicit
Const N = 10
Dim Nums()
ReDim Nums(N)
Randomize
Dim i
For i = 0 To N
' Randomize the Numbers as Integers
Nums(i) = Int(Rnd() * (N * 2))
Next
' Print out the Number Array
Sub PrintNum(Msg, arr)
Dim i, s
s = Msg
For i = 0 To UBound(arr)
s = s & " " & arr(i)
Next
Print s
End Sub
Sub InsertionSort(ByRef arr)
Dim j, i, N, x
' Upper Bound of Array
N = UBound(arr)
For i = 1 To N
j = i
x = arr(i)
Do While j > 0
If arr(j - 1) > x Then
' Shift Big Numbers to The Right
arr(j) = arr(j - 1)
j = j - 1
Else
Exit Do
End If
Loop
arr(j) = x
Next
End Sub
PrintNum "Before: ", Nums
Call InsertionSort(Nums)
PrintNum "After: ", Nums
答案 0 :(得分:0)
Split()是从单个输入字符串中获取字符串/字母数组的简单方法。如:
Option Explicit
' Sort one dimensional array in place
Sub InsertionSort(ByRef arr)
Dim j, i, N, x
' Upper Bound of Array
N = UBound(arr)
For i = 1 To N
j = i
x = arr(i)
Do While j > 0
If arr(j - 1) > x Then
' Shift Big Numbers to The Right
arr(j) = arr(j - 1)
j = j - 1
Else
Exit Do
End If
Loop
arr(j) = x
Next
End Sub
Dim aaTests : aaTests = Array( _
Array("a few integers", Array(3, 2, 5, 1, 4)) _
, Array("a few letters", Split("b d c a d a")) _
, Array("a few words", Split("some words in arbitrary order")) _
, Array("numbers", Empty) _
, Array("strings", Empty) _
)
' Use fixed array, if you know the size at 'compile' time
Dim a(9), i
For i = 0 To UBound(a)
a(i) = CLng(1 + Fix(Rnd() * 20))
Next
aaTests(3)(1) = a
aaTests(4)(1) = Split(Join(aaTests(3)(1)))
Dim aTest
For Each aTest In aaTests
WScript.Echo "--------", aTest(0), TypeName(aTest(1)(0))
WScript.Echo "Before |" & Join(aTest(1), "|") & "|"
InsertionSort aTest(1)
WScript.Echo "After |" & Join(aTest(1), "|") & "|"
Next
输出:
cscript 48867059.vbs
-------- a few integers Integer
Before |3|2|5|1|4|
After |1|2|3|4|5|
-------- a few letters String
Before |b|d|c|a|d|a|
After |a|a|b|c|d|d|
-------- a few words String
Before |some|words|in|arbitrary|order|
After |arbitrary|in|order|some|words|
-------- numbers Long
Before |15|11|12|6|7|16|1|16|17|15|
After |1|6|7|11|12|15|15|16|16|17|
-------- strings String
Before |15|11|12|6|7|16|1|16|17|15|
After |1|11|12|15|15|16|16|17|6|7|
标记数字和数字字符串之间的差异;避免无用的货物邪教代码,例如' Dim a()' (没有大小的固定数组)或者叫做SomeSub(params)' (添加噪声以允许添加噪声())。