Dim d() As Integer
创新互联公司是网站建设专家,致力于互联网品牌建设与网络营销,专业领域包括做网站、成都网站制作、电商网站制作开发、微信小程序定制开发、微信营销、系统平台开发,与其他网站设计及系统开发公司不同,我们的整合解决方案结合了恒基网络品牌建设经验和互联网整合营销的理念,并将策略和执行紧密结合,且不断评估并优化我们的方案,为客户提供全方位的互联网品牌整合方案!
Dim n As Integer
Dim i As Integer
Dim j As Integer
Dim T As Integer
n = Val(InputBox("请输入n,确定数组的元素个数"))
ReDim d(n)
'用随机函数生成正整数数组
Randomize
For i = 1 To n
d(i) = Int(Rnd * 100 + 1)
Next i
'输出
For i = 1 To n
Print d(i),
Next i
'从小到大排序
For i = 1 To n - 1
For j = i + 1 To n
If d(i) d(j) Then
T = d(i)
d(i) = d(j)
d(j) = T
End If
Next j
Next i
'输出
For i = 1 To n
Print d(i),
Next i
你直接传一个数组进去,而且是一个结构体数组,array.sort怎么知道根据结构中的哪一个属性进行排序?放一个c#的代码你看看,VB和C#很相似的
class Program
{
static void Main(string[] args)
{
People[] p = new People[3]
{
new People{name="张三"},
new People{name="李四"},
new People{name="张二名"}
};
//重点传一个实现了IComparer接口的类进去,告诉Array.Sort怎么排序
Array.Sort(p, new PeopleCompare());
foreach (var item in p)
{
Console.WriteLine(item.name);
}
Console.ReadKey();
}
}
//People结构体,换成类一样的
public struct People
{
public string name { get; set; }
}
//实现了IComparer接口的类
public class PeopleCompare : IComparer
{
public int Compare(object x, object y)
{
People p1 = (People)x ;
People p2 = (People)y;
return p1.name.CompareTo(p2.name);
}
}
游戏中遇到这样的问题,需要将一组已知的数据打乱,按照以前和现在的做法,总结了以下方法。
方法一,最笨的菜鸟方法,也是容易想到的(幸好我没想过这种方法 :))
从已知数组中随机一个数,然后加入到另一个数组中,在加入之前,先检查是否已经加入过。
这种方法有很大运气成分,且数据越大,效率越低,超过一定数目,则程序几乎无法执行,会一直卡在那里,代码:
[java] view plain copy
package com.test;
import java.util.Random;
public class TestArray {
public static int runCount =0;//用于记录方法运算次数
窗体上添加3个标签,1个按钮,在按钮的单击事件里写代码,如下:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim a(,) As Integer = {{5, 6}, {1, 3}, {8, 9}, {72, 1}, {63, 4}}
Dim Temp As Integer
Dim i As Integer
Dim j As Integer
Dim x As Integer
Dim y As Integer
'显示排序前的数据
Label1.Text = "排序前数据:" vbCrLf
For i = 0 To 4
Label1.Text = Label1.Text a(i, 0) " " a(i, 1) vbCrLf
Next
For i = 0 To 3
For j = i + 1 To 4
If a(i, 0) a(j, 0) Then
Temp = a(i, 0)
a(i, 0) = a(j, 0)
a(j, 0) = Temp
Temp = a(i, 1)
a(i, 1) = a(j, 1)
a(j, 1) = Temp
End If
Next
Next
'显示排序前的数据
Label2.Text = "排序后数据:" vbCrLf
For i = 0 To 4
Label2.Text = Label2.Text a(i, 0) " " a(i, 1) vbCrLf
Next
'把第3行元素赋予X,Y
x = a(2, 0)
y = a(2, 1)
'输出X,Y
Label3.Text = "X=" x vbCrLf "Y=" y
End Sub