学习网考试学习资料

Gzu521.com

计算机等级考试二级VB常用算法(7):排序

全国计算机等级考试   点击:次   发布时间:2007-7-2   【字体: 】   来源:Gzu521.com
贵 州 学 习 网

1、算法说明数组中元素的插入和删除一般是在已固定序列的数组中插入或删除一个元素,使得插入或删除操作后的数组还是有序的。
基本思路:首先要找到插入位置或要删除的元素。
1) 插入

代码如下:
private sub command1_click()
dim a(10) as integer
dim i as integer, k as integer
for i = 0 to 9 '生成数组
a(i) = i * 3 + 1
print a(i);
next i
print
print "插入14"
for k = 0 to 9 '查找插入14在数组中的位置
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 '插入数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) \oS+%4RP%2cHNqC [ 本 资 料 来 源 于 贵 州 学 习 网 IT认证全国计算机等级考试 http://Www.gzU521.com ] \oS+%4RP%2cHNqC


[NextPage]
2、实战练习 1) 补充代码(2001秋二(8))
c盘根目录下文件data4.txt的内容是:2,4,6,8,10,1,3,5,7,9。下面程序的功能是将文件后半部分的奇数分别按序插入到前半部分的适当位置,得到的新数列是:1 2 3 4 5 6 7 8 9 10。(实现方法:第一次调整后的数列是:1 2 4 6 8 10 3 5 7 9第二次调整后的数列是: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))
下面程序得功能是将无序数组中相同得数只保留一个,其余得删除,并输出经过删除后的数组元素,删除相同数是通过将该数组元素后面的元素在数组内依次前移替换前一个元素的值实现的。数组各元素的值从文件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 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


责任编辑:gzu521

IT认证分类
计算机软件水平考试
全国计算机等级考试
思科认证
微软认证
ORACLE/CIW认证
Linux认证
JAVA认证
其它认证
分类推荐信息
更多...
大类最新文章
更多...