0% found this document useful (0 votes)
10 views

Data structures

The document provides an overview of various data structures, including arrays and two-dimensional arrays, along with their declaration, value assignment, and example programs in Visual Basic. It also covers sorting techniques like bubble sort, shell sort, and selection sort, as well as searching techniques such as linear and binary search, with accompanying code examples. Additionally, exercises are included to reinforce understanding of the concepts presented.

Uploaded by

Daniel KK
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Data structures

The document provides an overview of various data structures, including arrays and two-dimensional arrays, along with their declaration, value assignment, and example programs in Visual Basic. It also covers sorting techniques like bubble sort, shell sort, and selection sort, as well as searching techniques such as linear and binary search, with accompanying code examples. Additionally, exercises are included to reinforce understanding of the concepts presented.

Uploaded by

Daniel KK
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

DATA STRUCTURES

Types of data structures


- Arrays
- Records
- Pointer
- Stacks and queues
- Sets
- Files
Sort Techniques
- Bubble shell
- Selection
Search Techniques
- Binary search
- Linear search

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.

One dimensional array


Declaring an array
To declare an array use the statement Dim ArrayName (n) As Datatype, where n
stands for the number of elements in the array e.g
Dim scores (4) as integer is an array that will hold five integer values
Assigning values to an array
Example
To assign a numeric value to location 4 of the array scores we use the statement
scores (4) = 90
To display a value held in location 3 of the array scores we use the statement
picresult.print scores (3)
NB: if the array is very large and you wish to read or enter values in it, it could be
very tedious entering a value cell by cell i.e score (0) = 10 score(1) = 2.. score (n) = x
To avoid this, the for loop can be used. Remember this loop is used where the number
of iterations are predetermined hence its suitability for use with arrays.
NB: The array declaration can also be adjusted as follows :
Dim A(1 to 5) as integer
In this case the array variable A is declared to hold five elements but we have forced
the first available location in the array to be 1.
Example (on one dimension array)
A V.B program to prompt the user for five integer values to be stored in array then
display them.

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.

Dim A (4) as interger


Private sub cimddisplay – click( )
Dim I as integer, j as integer for I = 0 to 4
A(i) = inputbox (“enter array value”, “arrays”)
Next i
For J = 4 to 0
Picdisplay. Print A(j)
Next j
End sub

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:

Math Eng Kisw Science Total


- - - - -
- - - - -
- - - - -
- - - - -
- - - - -

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.

Math Eng Kisw Science Total Average


- - - - - -
- - - - - -
- - - - - -
- - - - - -
- - - - - -

SORTING AND SEARCHING


SORTING
Is an algorithm for ordering an array.
a).bubble sort
Is an algorithm that compares adjacent elements and swaps those that are out of order. This
process is repeated enough times the list will be ordered. The steps for each pass through the
list are as follows:
st nd
1.compare the 1 and 2 item if they are out of order swap them
nd rd
2.compare the 2 and the 3 items if they are out of order swap them
3.repeat this process for all the remaining pairs, the final comparison and the possible swap
nd
are between the 2 last and the last element

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

Private sub form_load( )


Num (1) = 60
Num (2) = 3
Num (3) = 90
Num (4) = 7
Num (5) = 14
End sub
Exercise
Modify so that the above program prompts the user to enter the values to be sorted instead of
being assigned to array on form_load.

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.

Again, there was a swap, so keep the

There were no swaps for the current gap of 2, so Next Gap = Int([Previous Gap] / 2) = Int(2 / 2) = 1

Because there was a swap (actually two


swaps), keep the same gap.

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

Private sub cmdsort – click ( )


‘sort and display elements
call sortdata()
call showData()
End sub

Private sub sortData( )


Dim gap as integer, Doneflag as boolean
Dim index as integer, temp as integer
Gap = int (n/2)
Do while gap > = 1
Do
Doneflag = true
For index = 1 to n-gap
If num(index) > num (index + gap) then
Temp = num (index)
Num (index) = num(index + gap)
Num (index + gap) = temp
Done flag = false
End if
Next index
Loop until (doneflag = true)
Gap = int(gap/2)
Loop
End sub

Private sub showdata( )


Dim i as integer
For i = 1 to 5
Picsorted.Print num(i)
Next i
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

Private sub form _load()


Name (1)=”mike”
Name(2)= “Zachary”
Name(3)= “Abel”
Name (4)= “James”
Name(5)= “William”
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

Dim list(1 to 5) as integer


Private sub cmdlinearsearch_Click()
Dim key as integer, i as integer
Key = Inputbox (“key in element to search “, “search”)
‘Initialize first location to search from
i= 1
While (list(i) <> key) AND (i <> 6)
i = i +1 ‘check the next location
Wend
If (list(i) = key) Then
Picresult.print “element found”
Else
Picresult.print ”elememt not found”
End if
End sub

Private sub form_load()


List(1)= 7
List(2) = 2
List (3)= 4
List (4)= 10
List (5) =3
End sub

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

private sub form_load()


list (1)= 10
list(2)=20
list(3) =30
list(4)=40
list(5)=60
End sub
FILES
SEQUENTIAL FILES
Creating sequential files
1. Choose a file nam.A file name contain up to 255 characters consisting letter, digits
and a few other assorted characters but including spaces and periods
2. Choose a number from 1 through 511 to be the reference number of the file, while the
file is in use it will be identified by this number
3. Execute the statement open “filespec” FOR OUTPUT AS #n. where n is the
reference number. This process is referred to as opening a file for output .It allows
data to be output from computer and recorded in the specified files.
4. Place data into the file with the write#n statements e.g if a is string then the statement
write #n, a writes the string surrounded by quotation marks into the file.
If c is a number then the statement write #n, c writes the number c without any
leading or trailing spaces in the file number.
5. After the data has been recorded in the file, execute close # n whenever n is the
reference number. This statement breaks the communication link with the file and
dissociates the number n from the file
Example
The following program illustrates the different statements of the write statement. Notice the
absence of the leading & trailing spaces for numbers and the presence of quotation marks
surrounding strings

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.

ADDING ITEMS TO A SEQUENTIAL FILE


Execute the statement;
Open “filespec“ for append as #n
The append option for opening the file is intended to adding data to an existing file.
Example
Code to create a file and add data to an existing file using append
a).UI
Cmdsearch cmddisplaycontents

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

Private sub cmddisplaycontents_Click()


Dim num as integer
Open “c: \ numberlist.txt” for input as #1
Do while not EOF(1)
Input # 1, num
Me.print, num
Loop
Close# 1
Msgbox “contents diplayed”
End sub
Copying contents of numberlist file to numberlistcopyfile
private sub cmdcopyfile_click()
dim num as integer
open “C : \ numberlist.txt “for input as # 1
open “C : \ numberlistcopy.txt” for append as #2
Do until EDF(1)
input#1, num
print#2,num
Loop
close # 1
close # 2
msgbox” contents copied”
End sub
Searching for file contents
private sub cmdsearch_click()
dim num2search as integer, num as integer
open “C ; \numberlist.txt” for imput as #1
Do while (num<>num2search) and NOT EOF(1)
INPUT#1,num
Loop
If num2search=num Then
Me.print,num2search
Msgbox”contents displayed”
Else
Msgbox”no such record”
End if
Close # 1
End sub

RANDOM ACCESS FILES

A random-access file is like an array of records stored on a disk. The records


are numbered 1, 2, 3, and so on, and can be referred to by their numbers.
Therefore, a random-access file resembles a box of index cards, each having a
numbered tab. Any card can be selected from thbox without first reading
every index card preceding it; similarly, any record of a random-access file
can be read without having to read every record preceding it.
One statement suffices to open a random-access file for all purposes: creating,
appending, writing, and reading. Suppose a record type has been defined
with a Type block and a record variable, called recVar, has been declared with
a Dim statement. Then after the statement

Open “filespec” For Random As #n


is executed, records may be written, read, added, and changed. The file is
referred to by the number n. Each record will have as many characters as
allotted to each value of recVar. Suppose appropriate Type, Dim, and Open
statements have been executed. The two-step
procedure for entering a record into the file is as follows.
1. Assign a value to each field of a record variable.
2. Place the data into record r of file #n with the statement

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

State name Txtcollege


txtstate
abbreviation txtyrfounded
cmddone
Y. founded

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

private sub cmddone_click()


close#1
end sub
private sub form_load()
Dim college collegeData
Open”C : \ colleges” for random as #1
Recordnum = 0
End sub
Example
Displaying the contents of a random file
cmddisplay
Display

picoutput

Private sub cmddisplay_click()


Dim recordnum as integer
Dim college as collegedata
open “C : \ colleges.txt” for random as # 1
picoutput .cls
picoutput.print ”colleges”; tab(30); “state”;tab(45); “ year founded”
for recordnum=1 to 5
get #1, recordnum,college
picoutput.print college.nam;tab(30); college.state; tab(45); college.yrfounded
next recordnum
close #1
end sub

You might also like