Data structures
Data structures
DATA STRUCTURES
Arrays
Is a data structure that stores several data items of the same type. The figure below shows
how data of type integer is stored in an array.
20 30 80 120 200 250
index 0 1 2 3 4 5
The array has cells. The numbers 0 to 5 are called array indices or subscripts. In V.B
an array starts from cell 0 as shown in the table.
frmdisplay
Display
picdisplay
DISPLAY
cmdDisplay
b).Code
Private sub cmdDisplay – click( )
Dim A(4) as integer
Dim i as integer, j as integer
For i = 0 to 4
A (i) = inputBox (“enter array value” ,“arrays”)
Next i
For j = 0 to 4
Picdisplay.Print A(j)
Next j
End sub
Example
A VB program to prompt user for an array of 3 integer elements, compute and display
their sum
a).UI
frmsumarray
Sum array
Picsum
cmdcomput
COMPUTE
b).Code
Private sub cmdcompute _click()
Dim num (1 to 3) as integer
Dim i as integer, sum as integer
Sum = 0
For i = 1 to 3
Num (i) = InputBox (“enter array value,”Array”)
sum = sum + num(i)
Next i
Picsum.Print “sum of values is “, sum
End sub
Exercise
Rewrite example 1. On arrays so that elements are displayed in reverse in which they
are inputed.
2. Rewrite example 2 so that the average of the three inputed array values is also
computed and displayed.
Code
Dim num (1 to 3) as interger private sub cmdcalculate – clicki) dim I as integer, sum
as integer
Dim average as integer
Sum= 0
For I = 1 to 3
Num (i) = input Box (“enter array value”, arrays”)
Sum = sum + num(i)
Next i
Average = sum/3
Picsum print “sum of value is “, sum
Picsum, print “average of value is “ average
End sub.
TWO DIMENSIONAL ARRAYS
A two dimensional array is a data structure in which elements are arranged in rows
and columns. Two subscripts are used to identify an item e.g score(2,4)
rd th
Means 3 row 5 colum this is because the array was declared as from row 0 as
follows:
Dim score (0 to 2, 0 to 4) as integer OR
Dim score (2, 4) as integer
0 1 2 3 4
0
1
2
3
4 Score (2,4)
Example
A program to accept an array of 4 marks from 5 different students, calculate and
display total marks for each student alongside the marks on the form in the format
shown below:
a).UI
frmmarks
Total marks
cmdcompute
COMPUTE
b).Code
Private sub cmdcompute_click ( )
Dim studmarks (1 to 5, 1 to 4) as integer
Dim student as integer, mark as integer, col As integer
Dim sum (1 to 5) as integer
Col = 1
Me.print ”math”, Eng”, Kisw”, “Science”, “Total”
For student = 1 to 5
sum (student) = 0
For mark = 1 to 4
studmarks (student, mark) = inputbox (“key in student marks’, “marks” )
sum (student) = sum(student) + studmarks(student, mark)
Me.print tab(col);studmarks(student, mark); ‘print information starting from column 1
col = col + 6
If col > 20 Then
Me.print tab(col);sum(student) ‘print sum of marks for student and begin newline
col = 1 ‘reset column to start printing next information from column 1
End if
Next mark
Next student
End sub
Exercise
1. Write a vb program to assign the value 65 to all the locations of a 4 x 4 array and
display them in a table as shown
65 65 65 65
65 65 65 65
65 65 65 65
65 65 65 65
2. Rewrite our previous example on two dimensional array so that the average mark
for each student is also computed and displayed alongside other values as shown.
Illustration of how the elements list of names are sorted in ascending order using bubble
sort(Illustration Page 193-VBA beginner how to…)
Example
A program to sort a list of 5 numbers assigned to an array in ascending order using bubble
sort.
a).UI
frmBubbleSort
Bubble Sort
picsorted
sort
cmdsort
b).Code
‘General declaration
Dim num (1 to 5) as integer
Private sub cmdsort_click ( )
Dim pass as integer, compare as integer, temp as integer
dim i as integer,
for pass = 1 to 5
for compar = 1 to 4
If num(compar) > num(compar+1) Then
temp = num(compar)
num(compar) = num(compar+1)
num (compar+1) = temp
End if
Next compar
Next pass
Picsorted.print ”sorted elements are : “
For i = 1 to 5
Picsorted. print num(i)
Next i
End sub
SHELL SORT
The bubble sort is easy to understand and program. However it is too slow for long lists.
The shell sort is much more efficient in such cases. It compares distant items first and works
its way down to nearby items. The interval separating the compared items is called the gap.
The gap begins at one-half (½) the length of the list and it is successfully halved until
eventually each item is compared with its neighbor as in the bubble sort. The algorithm for a
list of n items is as follows:-
1. Begin with a gap of g = int (n/2)
2. Compare items 1 and 1 + g, 2 and 2 + g , ----- n-g and n ,swap any pairs that are out
of order
3. Repeat step two until no swaps are made for gap g.
4. Halve the value of g
5. Repeat step 2,3 and 4 until the value of g is zero .
The shell sort is illustrated below. The elements are sorted in ascending order, crossing
arrows indicate that a swap occurred.
Elements to be sorted are names: pebbles barney William, Fred, Dino
Initial gap = int (num of items/2) = int(5/2) = 2
Because there was a swap, use the same gap for the second pass.
There were no swaps for the current gap of 2, so Next Gap = Int([Previous Gap] / 2) = Int(2 / 2) = 1
Because there were no swaps for the current gap, then Next Gap = Int([Previous
Gap] / 2) = Int(1 / 2) = 0 and the Shell sort is complete.
Notice that the Shell sort required 14 comparisons to sort the list whereas the bubble sort
required only 10 comparisons for the same list. This illustrates the fact that for very short
lists, the bubble sort is preferable; however, for lists of 30 items or more, the Shell sort will
consistently outperform the bubble sort.
Example
Program that sorts a list of five integers in ascending order using shell sort
a).UI
frmShellSort
Shell Sort
picsorted
sort
cmdsort
b).code
‘General declaration
Dim num (1 to 5) as integer
const n as integer = 5
Private sub form _load( )
‘Read the numbers into array
num (1) = 60
num (2) = 90
num(3) = 40
num(4) = 30
num(5) = 80
End sub
Selection sort
st
In selection sort the item in the 1 position is compared with the other elements. If the
elements being compared are not in order they are swapped.
Illustration on how the elements 9, 6, 2, 10 are sorted in ascending order
9 6 2 2
st
6 9 9 9 1 pass
2 2 6 6
10 10 10 10
2 2 2 2 2
nd rd
9 6 6 2 pass 6 6 3 pass
6 9 9 9 9
10 10 10 10 10
Example
A program to sort a list of five names in ascending order using selection technique.
a).UI
frmSelectionSort
Selection Sort
picsorted
sort
cmdsort
‘General declaration
Dim name (1 to 5) as string
Private sub cmdsort_click()
Dim passnum as integer, compar as integer
For passnum = 1 to 4
For compar = passnum + 1 to 5
If name (passnum) > name (compar) Then
Temp = name(passnum)
Name (passnum) = name(compare)
Name (compar) = temp
End if
Next compar
Next passnum
For i = 1 to 5
Picsorted.print name (i)
Next i
End sub
SEARCHING TECHNIQUES
1.Linear search/ sequential search
Compares the key (element being searched) successively with the elements in the search list.
If a match is found the program reports that the element is in the list( i.e found) otherwise the
program reports that the element is not in the list(i.e not found).
Example
A program to search for an element from an array
a).UI
frmLinear
Searching
picresult
sort
cmdlinearsearch
b).Code
2. Binary Search
Works on a sorted list,
i. Divides an array by half by finding the middle element in the array i.e
middle element = first + last/2
ii. It then compares the middle element with the key.
a. If the middle element is greater than the key then the last location is computed by
last =middle -1 and search proceeds to the first half of array.
b. If the middle element is less than the key then the new first location is computed by
first = middle + 1 and search proceeds to the second half of the array.
c. If the middle element is equal to the key the search is over and the program reports
that the element is in the list otherwise program displays that the element was not
found.
Example
A program to search for an element from an array
a).UI
frmBinarysearch
Searching
picresult
sort
cmdsearch
b).code
dim list(1 to 5) As integer private
sub cmdsearch _(Click) dim key
as integer, flag as boolean
key = inputbox (“enter value to search”,”search”)
dim first as integer, middle as integer
dim last as integer
flag = false
first = 1
last = 5
Do while (first <= last) and (flag = false)
middle = int((first + last )/2)
Select case list(middle)
case is = key
flag = true
case is > key
last = middle-1
case is < key
first = middle + 1
End select
Loop
If (flag=true)Then
picresult.print ”found”
else
picresult.print “not found”
end if
End sub
a).UI
Create Cmdcreatefile
b).Code
Private sub cmdcreatefile_click()
Dim name1 as string, name2 as string
Dim num as integer
Num = 80
Name1 = “Eniac”
Name2 = “Mauldily”
Open “C: \pioneer.txt “ for output as # 1
Write # 1, “Eniac”, 1946, num
Write # 1,1946, name1, name2
Write #1, 14*139, “J.P” & name1, name2,”joe”
Close #1
End sub
N/B : If an existing sequential file is opened for file mode output. The computer will erase the
existing data and create a new empty file.
Cmdcopyfile cmdcreatefile
search Display
Create
Copy to file
b).Code
Private sub cmdcreatefile_Click()
Dim intmsg as integer
Dim num as integer , i as integer
Open “C : \numberlist.txt” for append as #1
Intmsg = msgbox (“numberlist.txt opened successfully”)
For num = 1 to 6
i = Inputbox (“enter number to store in file “)
Write # 1,i Next num
Intmsg=msgbox(“numberlist.txt closed”)
Close # 1
End sub
Example
Displaying contents of a sequential file (program)
Notes:
Open “number.txt” for input is #1
Input mode - opens an existing file for a read operation
Put #n, r, recVar where recVar is the record variable from Step 1.
Example
The following program creates and writes records to the random access file known as
colleges.txt
Add Done
cmdadd
‘module.BAS
Public type collegeData
nam as string *30
state as string*20
yrfounded as integer
end type
‘general declaration
Dim recordnum as integer
Private sub cmdadd_click()
dim college as collegeData
college.nam=txtcollege.text
college.state = txtstate.text
college.yrfonded = val(txtYrfounded.text)
recordnum = recordnum+1
put #1 ,recordnum,college
txtcollege.text =””
txt y founded.text = “”
txtcollege.setfocus
End sub
picoutput