8.
0 DATA STRUCTURES
Specific Objectives
By the end of this topic, the trainee should be able to:
1. Explain the meaning of data structures
2. Describe different types of data structures
3. Describe various sort techniques
4. Describe various search techniques
CONTENT
Description of data structures
Types of data structures
Sort techniques
Search techniques
ARRAYS
Introduction to Arrays
By definition, an array is a list of variables with the same data type and name. When we work
with a single item, we only need to use one variable. However, if we have a list of items which
are of similar type to deal with, we need to declare an array of variables instead of using a
variable for each item
An array is a consecutive group of memory locations that all have the same name and the same
type. To refer to a particular location or element in the array, we specify the array name and the
array element position number.
The Individual elements of an array are identified using an index. Arrays have upper and lower
bounds and the elements have to lie within those bounds. Each index number in an array is
allocated individual memory space and therefore users must evade declaring arrays of larger size
than required.
Declaring arrays
Arrays occupy space in memory. The programmer specifies the array type and the number of
elements required by the array so that the compiler may reserve the appropriate amount of
memory. Arrays may be declared as Public (in a code module), module or local. Module arrays
are declared in the general declarations using keyword Dim or Private. Local arrays are declared
in a procedure using Dim or Static. Array must be declared explicitly with keyword "As".
1
The syntax for declaring an array is:
[Dim | Private | Public | Static | Global] arrayname([lowerbound To] upperbound[, …])[As
datatype]
Sample declarations for a one-dimensional array:
Array Declaration Notes
Dim aintCount(9) As Integer declares a 10-element array, indexed 0 to 9
Dim aintCount(0 To 9) As Integer same as above, with explicit lower bound
Dim aintCount(1 To 10) As Integer declares a 10-element array, indexed 1 To 10
Dim aintCount(3 To 12) As Integer declares a 10-element array, indexed 3 To 12
Dim aintCount(-4 To 5) As Integer declares a 10-element array, indexed -4 To 5
Dim aintCount() As Integer declares a variable-length array whose bounds will
be determined at run-time
Note from the above declarations that the lower bound is not restricted to 0 or 1, and it can even
be negative.
To refer to an individual element of an array in a procedural statement, place the desired index in
parentheses next to the array name. For example, the following statement will display the 5th
element of aintCount on the form (assuming the first or second declaration above):
Print aintCount(4)
Sample declarations for multi-dimensional arrays:
Array Declaration Notes
Dim asngSales(1 To 4, 1 To 5) As Single declares a 2-dimensional array (four rows
indexed 1 to 4, by five columns indexed
1 to 5)
Dim asngResults(3, 1 To 12, 2 To 6) As Single declares a 3-dimensional array (the first
dimension has four elements indexed 0 to
3, within that, the second dimension has
12 elements indexed 1 to 12, and within
that, the third dimension has five
elements indexed 2 to 6)
To refer to an individual element of a multi-dimensional array in a procedural statement, place
the desired indices in parentheses next to the array name (you must have one index per
dimension, separated by commas).
2
Examples:
Print asngSales(2, 3)
Print asngResults(0, 11, 5)
Initializing Arrays
The most direct (although tedious) way to load constant data into an array is with individual
assignment statements:
Dim StudName(1 To 3) As String
StudName(1) = "Mary"
Option Base
As explained above, by default, if you do not explicitly code a lower bound, the lower bound of
an array is 0. However, there is a statement called Option Base, which, if you code Option Base
1, will force VB to default the lower bound of arrays to 1. The Option Base statement can only
have the number 0 or 1 after it, and 0 is the default – so you never need to code Option Base 0.
The Option Base statement, if used, would be coded at the beginning of a code module and is
enforced only at the module level. Recommendation: Do not use Option Base; explicitly code the
lower bound of your array declarations.
TYPES OF ARRAYS
There are two types of arrays in Visual Basic namely:
Fixed-size array : The size of array always remains the same-size doesn't change during the
program execution.
Dynamic array : The size of the array can be changed at the run time- size changes during the
program execution.
Fixed-sized Arrays
When an upper bound is specified in the declaration, a Fixed-array is created. The upper limit
should always be within the range of long data type.
3
Declaring a fixed-array
Dim numbers(5) As Integer
In the above illustration, numbers is the name of the array, and the number 5 included in the
parentheses is the upper limit of the array. The above declaration creates an array with 6
elements, with index numbers running from 0 to 5.
If we want to specify the lower limit, then the parentheses should include both the lower and
upper limit along with the To keyword. An example for this is given below.
Dim numbers (1 To 6 ) As Integer
In the above statement, an array of 6 elements is declared but with indexes running from 1 to 6.
A public array can be declared using the keyword Public instead of Dim as shown below.
Public numbers(5) As Integer
Dimension of an Array
An array can be one dimensional or multidimensional. One dimensional array is like a list of
items or a table that consists of one row of items or one column of items.
A two dimensional array is a table of items that make up of rows and columns.
The format for a one dimensional array is ArrayName(x), the format for a two dimensional array
is ArrayName(x,y) and a three dimensional array is ArrayName(x,y,z) . Normally it is sufficient
to use one dimensional and two dimensional array ,you only need to use higher dimensional
arrays if you need to deal with more complex problems. Let me illustrate the arrays with tables.
One dimension array
Student Name(1) Name(2) Name(3) Name(4) Name(5) Name(6)
Name
Two dimension array
Name(1,1) Name(1,2) Name(1,3) Name(1,4)
Name(2,1) Name(2,2) Name(2,3) Name(2,4)
Name(3,1) Name(3,2) Name(3,3) Name(3,4)
Multidimensional Arrays
Arrays can have multiple dimensions. A common use of multidimensional arrays is to represent
tables of values consisting of information arranged in rows and columns. To identify a particular
table element, we must specify two indexes: The first (by convention) identifies the element's
row and the second (by convention) identifies the element's column.
4
Tables or arrays that require two indexes to identify a particular element are called two
dimensional arrays. Note that multidimensional arrays can have more than two dimensions.
Visual Basic supports at least 60 array dimensions, but most people will need to use more than
two or three dimensional-arrays.
The following statement declares a two-dimensional array 50 by 50 array within a procedure.
Dim AvgMarks ( 50, 50)
It is also possible to define the lower limits for one or both the dimensions as for fixed size
arrays. An example for this is given here.
Dim Marks ( 101 To 200, 1 To 100)
An example for three dimensional-array with defined lower limits is given below.
Dim Details( 101 To 200, 1 To 100, 1 To 100)
EXAMPLE OF TWO DIMENSIONAL
Private Sub Command1_Click()
'Program to Input values in a two dimensional array
Dim num(4, 4) As Long
Dim i, j As Integer
'Input of the numbers
For i = 1 To 4
For j = 1 To 4
num(i, j) = InputBox("Enter a number")
Next j
Next i
'Output of the ten numbers on the form
For j = 1 To 4
Print "The "& j; "Row"
For i = 1 To 4
Print num(i, j)
Next i
Next j
End Sub
5
Types of arrays
Static and dynamic arrays
Static arrays
Static arrays must include a fixed number of items, and this number must be known at compile
time so that the compiler can set aside the necessary amount of memory. You create a static array
using a Dim statement with a constant argument:
This is a static array.
Dim Names(100) As String
Visual Basic starts indexing the array with 0. Therefore, the preceding array actually holds 101
items.
Dynamic arrays
Most programs don't use static arrays because programmers rarely know at compile time how
many items you need and also because static arrays can't be resized during execution. Both these
issues are solved by dynamic arrays. You declare and create dynamic arrays in two distinct steps.
In general, you declare the array to account for its visibility (for example, at the beginning of a
module if you want to make it visible by all the procedures of the module) using a Dim
command with an empty pair of brackets. Then you create the array when you actually need it,
using a ReDim statement:
An array defined in a BAS module (with Private scope)
Dim Customers() As String
...
Sub Main()
' Here you create the array.
ReDim Customer(1000) As String
End Sub
If you're creating an array that's local to a procedure, you can do everything with a single ReDim
statement:
Sub PrintReport()
' This array is visible only to the procedure.
ReDim Customers(1000) As String
' ...
End Sub
If you don't specify the lower index of an array, Visual Basic assumes it to be 0, unless an Option
Base 1 statement is placed at the beginning of the module.
ReDim Customers(1 To 1000) As String
6
Dynamic arrays can be re-created at will, each time with a different number of items. When you
re-create a dynamic array, its contents are reset to 0 (or to an empty string) and you lose the data
it contains. If you want to resize an array without losing its contents, use the ReDim Preserve
command:
ReDim PreserveCustomers(2000) As String
When you're resizing an array, you can't change the number of its dimensions nor the type of the
values it contains. Moreover, when you're using ReDim Preserve on a multidimensional array,
you can resize only its last dimension:
ReDim Cells(1 To 100, 10) As Integer
...
ReDim Preserve Cells(1 To 100, 20) As Integer ' This works.
ReDim Preserve Cells(1 To 200, 20) As Integer ' This doesn't.
EXAMPLE
The program accepts data entry through an input box and displays the entries in the form
itself. As you can see, this program will only allows a user to enter 10 names each time he
click on the start button.
Private Sub Command1_Click()
Dim studentName(10) As String
Dim num As Integer
For num = 1 To 10
studentName(num) = InputBox("Enter the student name", "Enter Name", "", 1500, 4500)
If studentName(num) <> "" Then
Form1.Print studentName(num)
Else
End
End If
Next
End Sub
EXAMPLE
The program accepts data entries through an InputBox and displays the items in a list box.
Private Sub Command1_Click()
Dim studentName(10) As String
Dim num As Integer
For num = 1 To 10
studentName(num) = InputBox("Enter the student name")
List1.AddItem studentName(num)
Next
End Sub
7
EXAMPLE
The following example uses a For/Next loop to load an array of 10 integers with random
numbers between 1 and 100, then uses a second For/Next loop to print out the results.
Private Sub Command1_Click()
Dim aintRandomNum(1 To 10) As Integer
Dim intX As Integer
Randomize
' load the "aintRandomNum" array with random numbers between 1 and 100 ...
For intX = 1 To 10
aintRandomNum(intX) = Int(100 * Rnd + 1)
Next
' display the contents of the "aintRandomNum" array ...
For intX = 1 To 10
Print aintRandomNum(intX)
Next
End Sub
EXAMPLE OF ONE DIMENSIONAL ARRAY
Private Sub cmdarray2_Click()
'Program to demonstrate the use of redim Statemnet
Dim num() As Long
Dim k, i As Integer
k = InputBox("How many Values Do you want to enter", "Numbers", 10)
ReDim num(k)
'Input of the numbers
For i = 1 To k
num(i) = InputBox("Enter a number")
Next i
'Output of the ten numbers on the form
For i = 1 To k
Print num(i)
Next i
End Sub
8
CONTROL ARRAYS
Similar to arrays of variables, you can group a set of controls together as an array. The following
facts apply to control arrays:
The set of controls that form a control array must be all of the same type (all textboxes, all labels,
all option buttons, etc.)
You set up a control array by naming one or more controls of the same type the same name and
set the Index property of each control in the array to a non-negative value (i.e., the controls in
the control array are usually indexed from 0 to one less than the number of controls in the array).
The properties of the controls in the control array can vary: i.e., some members can be visible or
not, they can be sized differently, they can have different fonts or colors, etc.
To refer to a member of a control array, the syntax is:
ControlName(Index)[.Property]
For example, to refer to the Text property of the first element of an array of textboxes called
txtField, you would use:
txtField(0).Text
All the members of the control array share the same event procedure for example, if you have a
control array of 10 textboxes call txtField, indexed 0 to 9, you will not have 10 different
GotFocus events you will just have one that is shared amongst the 10 members. To differentiate
which member of the control array is being acted upon, VB will automatically pass an Index
parameter to the event procedure.
For example, the GotFocus event procedure for the txtField control array might look like this:
Private Sub txtField_GotFocus(Index As Integer)
txtField(Index).SelStart = 0
txtField(Index).SelLength = Len(txtField(Index).Text)
End Sub
- or -
Private Sub txtField_GotFocus(Index As Integer)
With txtField(Index)
.SelStart = 0
.SelLength = Len(.Text)
End With
End Sub
To build a sample application that uses a control array, perform the following steps:
Click the control once to select it. Then Copy it. Click on an open area of the form and Paste.
The following message will appear: You already have a control named 'cmdTest'. Do you
want to create a control array? Respond Yes. The pasted control will appear in the upper left-
hand corner of the form. Move the pasted control toward the bottom, next the original. By
9
answering yes to the prompt, VB automatically set the Index property of the original command
button to 0 and set the Index of the pasted control to 1.
Handling Files
A file is simply a series of related bytes located on a disk. When your program accesses a file it
must assume what the bytes are supposed to represent.
Visual Basic allows three types of access:-
1. Sequential
2. Random
3. Binary
Sequential Access is for plain ASCII text or a text formatting sequence.
Random Access assumes a file is composed of a set of equal length records and is stored as
binary information.
Binary files allow you to store data in any format. It is similar to Random but no assumptions are
made about the data type or record length. You must know precisely how the data is written to
the file to retrieve it correctly.
Reading and Writing Files
Visual Basic works with files in a different way from other programs. There are a number of
ways that Visual Basic handles files.
The Command to open a file is Open and Close to close any of the 3 types of files.
File Functions
The following functions can be used with all three types of file.
Dir FileLen LOF
EOF FreeFile Seek
FileCopy GetAttr SetAttr
FileDateTime Loc
In addition the following is a list of statements available for each type.
Statement Sequential Random Binary
Close
Get
Input()
Input #
Line Input#
Open
Print #
Put
Type...End Type
Write #
10
Binary and Sequential Files
Visual Basic provides two other modes for opening files; Binary and Sequential. Binary access
mode allows you to write groups of bytes anywhere in the file. This mode gives you most control
over a file but requires a lot of work. Binary files use the Get and Put statements to read and
write data.
Sequential files allow you to read a file from start to finish, one line at a time. This is useful if
you want to read lines of text, but you don‟t need to go backward through the file. The
statements to write lines are Print# or Write# and those to read lines are Input# or LineInput#.
Sequential Access
This type of access works best when you wish to process files consisting of text e.g. text editor or
simple word processor.
With this type you can open it for Input, Output or Append with the following:
Open file For [Input|Output|Append] As filenumber [Len = buffersize]
If opening for input it must already exist otherwise an error occurs. If you open a non-existent
file for Output or Append however the open statement will first create the file then open it.
After opening you must close it with the Close statement before using it for another operation.
Examples
To create a file , we use the following command
Open "fileName" For Output As #fileNumber
Each file created must have a file name and a file number for identification. As for the file name,
you must also specify the path where the file will reside.
Examples:
Open "c:\My Documents\sample.txt" For Output As #1
will create a text file by the name of sample.txt in My Document folder in C drive. The
accompanied file number is 1. If you wish to create and save the file in D drive, simply change
the path, as follows"
Open "D:\sample.txt" For Output As #1
Reading a file
To read a file created above, you can use the input # statement. However, we can only read the
file according to the format when it was written. You have to open the file according to its file
number and the variable that hold the data. We also need to declare the variable using the DIM
command.
11
Sample Program: Reading file
Private Sub Reading_Click()
Dim variable1 As String
Open "c:\My Documents\sample.txt" For Input As #1
Input #1, variable1
Text1.Text = variable1
Close #1
End Sub
SORTING AND SEARCHING
A sort is an algorithm for ordering an array. Of the many different techniques for sorting anarray
we discuss two, the bubble sort and the Shell sort. Both require the interchange of valuesstored
in a pair of variables. If var1, var2, and temp are all variables of the same data type(such as all
String), then the statements
temp= var1
var1 = var2
var2 = temp
assignvar1‟s value to var2, and var2‟s value to var1.
EXAMPLE
Write a program to alphabetize two words supplied in text boxes.
Private Sub cmdAlphabetize_Click()
Dim firstWord As String, secondWord As String, temp As String
„Alphabetize two words
firstWord = txtFirstWord.Text
secondWord = txtSecondWord.Text
If firstWord > secondWord Then
temp = firstWord
firstWord = secondWord
secondWord = temp
End If
picResult.Cls
picResult.Print firstWord; “ before ”; secondWord
End Sub
BUBBLE SORT
The bubble sort is an algorithm that compares adjacent items and swaps those that are out
oforder. If this process is repeated enough times, the list will be ordered. Let‟s carry out
thisprocess on the list Pebbles, Barney, Wilma, Fred, Dino. The steps for each pass through the
listare as follows:
1. Compare the first and second items. If they are out of order, swap them.
2. Compare the second and third items. If they are out of order, swap them.
3. Repeat this pattern for all remaining pairs. The final comparison and possible swap are
between the second-to-last and last elements.
12
The first time through the list, this process is repeated to the end of the list. This is called
the first pass. After the first pass, the last item (Wilma) will be in its proper position.
Therefore,the second pass does not have to consider it and so requires one less comparison. At
theend of the second pass, the last two items will be in their proper position. (The items thatmust
have reached their proper position have been underlined.) Each successive pass requiresone less
comparison. After four passes, the last four items will be in their proper positions,and hence, the
first will be also.
Example: Bubble sort program
Dim nom(1 To 5) As String
Private Sub Command1_Click()
Dim passNum As Integer, i As Integer, temp As String
'Bubble sort names
nom(1) = InputBox("enter a string")
nom(2) = InputBox("enter a string")
nom(3) = InputBox("enter a string")
nom(4) = InputBox("enter a string")
For passNum = 1 To 4 'Number of passes is 1 less than number of items
For i = 1 To 5 - passNum 'Each pass needs 1 less comparison
If nom(i) > nom(i + 1) Then
temp = nom(i)
nom(i) = nom(i + 1)
nom(i + 1) = temp
End If
Next i
Next passNum
'Display alphabetized list
'picNames.Cls
For i = 1 To 5
Print nom(i),
Next i
End Sub
13
SHELL SORT
The bubble sort is easy to understand and program. However, it is too slow for really longlists.
The Shell sort, named for its inventor, Donald L. Shell, is much more efficient in suchcases. It
compares distant items first and works its way down to nearby items.
The interval separatingthe compared items is called the gap. The gap begins at one-half the
length of the listand is successively halved until eventually each item is compared with its
neighbour as in thebubble 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 2 until no swaps are made for gap g.
4. Halve the value of g.
5. Repeat Steps 2, 3, and 4 until the value of g is 0.
Example: On Shell sort
Create a file on drive c on a folder mtti and name it shoeparts.txt (the data in the file are
used)
Dim part(1 To 5) As String
Dim numParts As Integer
Private Sub SortData()
Dim gap As Integer, doneFlag As Boolean
Dim index As Integer, temp As String
'Shell sort shoe parts
gap = Int(numParts / 2)
Do While gap >= 1
Do
doneFlag = True
For index = 1 To numParts - gap
If part(index) > part(index + gap) Then
temp = part(index)
part(index) = part(index + gap)
part(index + gap) = temp
doneFlag = False
End If
Next index
Loop Until doneFlag = True 'Can also be written Loop Until doneFlag
gap = Int(gap / 2) 'Halve the length of the gap
Loop
End Sub
14
Private Sub showData()
Dim i As Integer 'Display sorted list of parts
'picParts.Cls
For i = 1 To numParts
Print part(i)
If i Mod 5 = 0 Then 'only put 5 items per line
Print
End If
Next i
End Sub
Private Sub CmdDisplay_Click()
Call SortData
Call showData
End Sub
Loads the data from a file
Private Sub Form_Load()
Open "c:\mtti\shoesparts.txt" For Input As #1
Do While (Not EOF(1)) And (numParts < UBound(part))
numParts = numParts + 1
Input #1, part(numParts)
Loop
'Text1.Text = part
Close #1
End Sub
SEARCHING
Suppose we had an array of 1000 names in alphabetical order and wanted to locate a specific
person in the list. One approach would be to start with the first name and consider each name
until a match was found. This process is called a sequential search. We would find a person
whose name begins with “A” rather quickly, but 1000 comparisons might be necessary to find a
person whose name begins with “Z.”
For much longer lists, searching could be a time consuming matter. However, when the list has
already been sorted into either ascending or descending order, there is a method, called a binary
search that shortens the task considerably.
Let us refer to the sought item as quarry. The binary search looks for quarry by determining in
which half of the list it lies. The other half is then discarded and the retained half is temporarily
regarded as the entire list. The process is repeated until the item is found. A flag can indicate if
quarry has been found. The algorithm for a binary search of an ascending list is as follows:
1. At each stage, denote the subscript of the first item in the retained list by first and the
subscript of the last item by last. Initially, the value of first is 1, the value of last is the
number of items in the list, and the value of flag is False.
2. Look at the middle item of the current list, the item having the subscript
middle= Int((first +last) / 2).
15
3. If the middle item is quarry, then flag is set to True and the search is over.
4. If the middle item is greater than quarry, then quarry should be in the first half of the list.
So the subscript of quarry must lie between first and middle [minus]1. That is, the new
value of last is middle – 1.
5. If the middle item is less than quarry, then quarry should be in the second half of the list
of possible items. So the subscript of quarry must lie between middle+ 1 and last. That is,
the new value of first is middle + 1.
6. Repeat Steps 2 through 5 until quarry is found or until the halving process uses up the
entire list. (When the entire list has been used up, first >last.) In the second case, quarry
was not in the original list.
Below is a the flowchart for a binary search
Example: Binary search code
Dim firm(1 To 5) As String
Dim numFirms As Integer
Private Sub Cmdsearch_Click()
Dim corp As String, result As String
corp = Trim(Text1.Text)
Call BinarySearch(corp, result)
'Display results of search
Print corp; “; ”; result
End Sub
16
Private Sub BinarySearch(corp As String, result As String)
Dim foundFlag As Boolean
Dim first As Integer, middle As Integer, last As Integer
'Array firm() assumed already ordered alphabetically
'Binary search of firm() for corp
foundFlag = False
first = 1
last = numparts
Do While (first <= last) And (Not foundFlag)
middle = Int((first + last) / 2)
Select Case (parts(middle))
Case corp
foundFlag = True
Case Is > corp
last = middle - 1
Case Is < corp
first = middle + 1
End Select
Loop
If foundFlag Then
result = “found”
Else
result = "not found"
End If
End Sub
Private Sub Form_Load()
Open "c:\mtti\shoesparts.txt" For Input As #1
Do While (Not EOF(1)) And (numParts < UBound(part))
numParts = numParts + 1
Input #1, part(numParts)
Loop
'Text1.Text = part
Close #1
End Sub
17