You are on page 1of 28

Table of contents

Table of contents..........................................................................................................................1
USER DEFINED SIMPLE TYPE DATA...................................................................................1
a) Enumerated type data...........................................................................................................1
b) Subrange..............................................................................................................................1
Utilizing User Defined Data Type...........................................................................................2
ARRAYS......................................................................................................................................3
a) One dimensional array.........................................................................................................3
b) Two Dimensional Array......................................................................................................4
c) Multi dimension arrays........................................................................................................4
d)Packed arrays .......................................................................................................................5
RECORDS...................................................................................................................................5
Processing a record...................................................................................................................7
SORTING.....................................................................................................................................7
a) Selection sort........................................................................................................................8
b) Bubble sort...........................................................................................................................8
c) Insertion Sort......................................................................................................................10
d) Quick Sort..........................................................................................................................10
e) Merge Sort..........................................................................................................................12
f) Shell Sort............................................................................................................................13
SEARCHING.............................................................................................................................13
a)Linear Search......................................................................................................................14
b) Binary Search.....................................................................................................................14
DATA STRUCTURES..............................................................................................................14
(a) Sets....................................................................................................................................14
Constructing a Set..................................................................................................................15
Operations with Sets...............................................................................................................16

(b) Stacks................................................................................................................................17
(c) Queues..............................................................................................................................19
(d) Linked Lists......................................................................................................................21
(e) Binary trees.......................................................................................................................23

1
USER DEFINED SIMPLE TYPE DATA
They are data types which are designed by the programmer to meet special purpose. They are
of two types
i.) Enumerated
ii.) Subrange

a) Enumerated type data


Consists of an ordered sequence of identifiers, where each identifier is interpreted as an
individual data item. These data items will collectively be associated with a particular name
which serves to identify the data type. The association between the name of the data type and
individual data items is established bt a type definition.

Type name = (data item1, data item2 ,….., data item 2);
Where name is the name of the enumerated data type and data item1 data item2 are actual data
items.
Example1
Type day =(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)
Var offdays:day;

Note data items are enclosed in parenthesis and separated by commas.


Example 2
type day =(sun, mon, tue, wed, thu, fri, sat);

Since enumerated type data are defined in an ordered sequence, relational operators may be
applied to them to form Boolean expression. Also the standard function pre and succ may be
used to determine which data items precede or succeed any data item
using example 2 above

Expression Value
Sun< tue True
Wed >= sat False
Mon <> fri True
Pred(fri)= thu True
Succ(fri)=sat True
Succ(tue)<> pred(thu) False

b) Subrange
A sub-range refers to some portion of the original range of an ordered simple data. Sub-range
type are the data items that fall within this sub-range, thus forming a subset contiguous ordered
data. The original data is referred to as the host data type.
The sub range concept can be applied to any set of ordered simple data. This includes
previously defined enumerated data as well as three of the standard types i.e integer, char,
Boolean.

1
The general form
Type name first data item.. last data item
Where
Name is the name of the sub-range data type .
First data item is the first of the ordered items within the subrange
Last data item is the las of the ordered data items

Examples
type day =(sun, mon, tue, wed, thu, fri, sat);
weekdays =mon..fri.
month =1..31;
caps =’a’..’z’;
var workdays,holidays: weekdays;
dayofthemonth: month;
hoursworked: 1..24;
grosspay,netpay: real;
employment: 1..999

Utilizing User Defined Data Type


Once enumerated and subrange data types have been defined, they can be used just as other
simple data items are used within apascal program this includes their use as control variables
in FOR and Case examples
for workkdays : mon to fri do
begin
writeln(workdays);
……
…….
end;

case workdays of
mon: writeln(‘the first work day’);
tue: writeln(‘the secondwork day’);
wed: writeln(‘the third work day’);
thu: writeln(‘the fourth work day’);
fri: writeln(‘the fifth work day’);
end;

2
ARRAYS

ARRAYS
Is a structured type data which is referred to by a single identifier. In many situations sets of
data items such as set of examination for a class may be conveniently arranged in to a
sequence. An array becomes easier to use in this case. Individual data items in an array are
often called elements.
There are three types of arrays
a) One dimensional array
b) Two dimensional array
c) Multi dimensional array

a) One dimensional array


it can be thought of as a list of data items, all of the same type , that they are
collectively referred to by the same name. Each individual array element (i.e each of the data
items) can be referred to by specifying the array name followed by an index, enclosed in
brackets. The general expression of an array is

List[1]
List[2]
List = .
.
.list[n]

The easier way to defined are array is to include it in a variable declaration

Var array name: array [index type] of type


The index type can be ordinal simple (i.e integer, char, Boolean or enumerated or a
subrange. The array it self can be of any type including structured types. Examples of
declarations
i). VAR List : ARRAY[1..100] OF Real;
ii). Type index= 1..100;
VAR List: ARRAY [index] of Real;
Individual array elements can be used in expressions, assignment statements,
read and write statements as though they are ordinary simple type variables. An
array element must be written sa the array name followed by an appropriate
index value enclosed in square brackets

3
b) Two Dimensional Array
Can be thought of as a table of data items consisting of rows and columns. Is a repetition of
one dimension array. The structure can be thought of as a matrix or grid structure. The first
dimension might refer to the row number and the second dimension to the column number

table[1,1] table[1,2] ….. table[1,n]


table[2,1] table[2,2] ….. table[2,n]
table[3,1] table[3,2] ….. table[3,n]
. . .
table =
. . .
. . .
. . .
. . .
. . .
table[m,1] table[m,2] ….. table[m,n]

The general expression


VAR array name : array [index 1 type, index 2 type ] of type
The index types can be ordinal, simple types(i.e integer char, boolen or enumerated) or
subranges. The array element must all be of the same type though they can be of any type.
Example of declarations
i.) Var table: array[1..60,1..150] of real;
ii.) Type index=1..60;
Index2=1..150;
Var: table :array [index1,index2] of real
iii.) Const limit1=60;
Limit2=150;
Type index1=1..limit1;
Index2=1..limit2;
Var table: array [index1,index2] of real

c) Multi dimension arrays


A three dimension array might be thought of as a collection of two dimensional array
(repetition) afour dimension array might be thought of as a repetition of a three dimensional
array etc . regardless of its dimension, an array always consists of a collection of data items of
the same type.
Examples
i.) Type twod= array[1..10,1..5] of integer;
Var threed:array[1..4] of twod;
ii.) Type threed= array[1..10,1..5,1..10] of integer;
Var fourd: array [1..4] of threed;

4
The method of access to the arrays will be through their respective indices for example
Threed[2,2,4]:=20;
Readln(threed[1,8,3]);
Writeln(foud[3,2,8,4]);

d)Packed arrays
some types of arrays can be defined so that they can utilize the computer’s memory more
efficiently by “packing” the data items close together. This feature allows a greater quantity of
information to be stored in a given amount of memory.
Example
Var list : packed array[1..4] of char
This feature is most effective with array elements of type char, boolen or enumerated or with
sub range type data. Storage economy gained by packing may offset by loss of computing
speed.

RECORDS
A record can be defined as a group of fields made up of different data items. In pascal we refer
a record as a collection of heterogeneous (different) types of data grouped together.. the entire
collection is referred to as a record. The individual components which are called fields or
members can be accessed and processed separately.
Defining a record
The general form of a record variable decaration is:
Var record name= record
Field1;
Field2;
.
.
Fieldn
End;
Where field1 represents the first field declaration, field2 represents the second field and sos on.
Each field declaration is written in manner that is similar to an individual variable declaration
i.e field name: type
Where field name is an identifier that represents the name of the field and type is their data
type of the item that will occupy the field. Therefore full declaration would be

Var record name= record


Field name 1: type;
Field name 2: type;
.
.
Field name n: type;
End;

5
Example
Var customer= RECORD
Custno: integer;
Custtype: char;
Custbalance: real
end

records can also be declared using type definition as in the following example
general form is

type record name= record


Field name 1: type;
Field name 2: type;
.
.
Field name n: type;
End;

Example 2
type account= RECORD
Custno: integer;
Custtype: char;
Custbalance: real
end
var
customer: account;
Individual fields can be associated with user defined types as well as standard data types
Example
type status=(current, overdue, delinquent);
account= RECORD
Custno: integer;
Custtype: char;
Custstatus=status;
Custbalance: real
end
var
customer: account;
or

type status=(current, overdue, delinquent);


line= ARRAY[1..80] of char;
account= RECORD
custname: line;

6
Custno: integer;
Custtype: char;
Custstatus=status;
Custbalance: real
End;
var
customer: account;

Example 3
type status=(current, overdue, delinquent);
line= ARRAY[1..80] of char;
date = record
month:1..12;
day: 1..31;
yeay: 1900..2100;
end;
account= RECORD
custname: line;
lastpayment: date;
Custno: integer;
Custtype: char;
Custstatus=status;
Custbalance: real
End;
var
customer: account;

you can declare several records using the same type


e.g
VAR customer, regular: account;

Processing a record

SORTING
Sorting is the process of rearranging an initially unordered sequence of records until they are
ordered with respect to all of or that part of each record designated as its key. Usually desired
result is that the records be placed in ascending order.
At least five considerations may influence the choice of an internal sorting algorithm:
1. Running time: How long does it take to sort n records and by what factor does this
time increase ib order to sort 2n records?
2. Memory space: Do main memory limitations force choice of an algorithm that sorts
“in place”(only one or two record spaces are needed beyond the space needed to hold n

7
records), or are there an additional n record spaces available beyond the space needed
to hold the data to be sorted?
3. Initial order: are the records known to be already ordered with just a few exceptions?.
This is not the usual situation algorithm may well be one that is not at all efficient
when the initial order of the records is essentially random.
4. Key range: Do record keys span a very large range or possibly only a very restricted
range (such as integers 0 to 999). Certain algorithm applicable to keys of narrow range
are not feasible for keys that span a large range.
5. Programming language: For reasons of availability, must a particular programming
language be used if so, does that language support recursion since many of the most
efficient internal sorting algorithms are most naturally expressed recursively.

The following sorting algorithms will be discussed


a) Selection sort
b) Bubble sort
c) Insertion sort
d) Quick sort
e) Shell sort
f) Merge sort
g) Binary sort

a) Selection sort
Selection sort involves looking thro all n records to find the one with smallest key, then thro
the remaining n-1 records a to find the one of the next smallest key, etc. by exchanging each
record of successively smaller key with appropriate record at the top of the unsorted sequence
of records, the records can be sorted in place, the length of the sorted sequence at the top
growing gradually longer as the length of the unsorted sequence at the bottom shrinks to zero.
Selection sort is slow. Selection sort is suitable for few records. Another advantage of this
algorithm is that records of successively larger key are identified on one by one, so that output
of the sorted list can proceed virtually in parallel with the sort itself.
Example
See sample programs

b) Bubble sort
Bubble sort is is based on obvious idea on the simplistic notion that if two adjacent records are
out of order they should be exchanged. If this is done to successive (overlapped) record pairs,
from the first thro the record pair that starts at the (n-1)st position, the original list will not
necessarily yet be sorted, but one can be sure that the record of the largest key (assuming an
ascending order sort) will have reached the end of the list. Then by repeating the process n-2
more times, the entire list is certain to be sorted. Successive phases of the sort are called
passes. Bubble sort is also known as exchange sort. Like selection sort this algorithm is very
slow.

8
The idea of bubble sort is just comparing all the data. The first data is compared to the second,
to the third, and so on until the end of the data. Then the second data compared to the third, to
the fourth, so on. Then the third data to the fourth and so on ... and so on.

Why it is called as the Bubble sort. It is because that the comparison and the swapping make
the desired data to gradually come up like a bubble. Example : Suppose we have data like this

5 3 8 4 1 7 6 2 (unsorted)

Follow the algorithm -- i.e. comparing the first and the second data : 5 and 3. 5 is greater than
3, hence it must be swapped out

3 5 8 4 1 7 6 2 (1st step)

Then the first and the third. Since 3 is smaller than 8, no swapping is necessary. Then the first
and the fourth : No swapping either. The first and the fifth -- since 1 is smaller than 3, it must
be swapped :

1 5 8 4 3 7 6 2 (4th step)

And so on, till the end of data, the sequence remains the same. Then the second with the third
-- no changes this time. The second with the fourth. Change must be done :

14853762
then becomes :
13854762

And so on :

12854763
12584763
12485763
12385764
12358764
12348765
12347865
12346875
12345876
12345786
12345687

Finally, sorted : 1 2 3 4 5 6 7 8

You see that smaller data comes up like bubble and bigger data sank down gradually, as you
may note the 8. That's why this method is called bubble sort.
Example

9
See sample programs

c) Insertion Sort
The insertion sort algorithm is likely to occur to anyone who is playing cards by simply
holding them in the hand and inserting them one by one into the proper position in the stack or
hand of already sorted items. In the computer version room has to be made for insertion of the
records at the top of the list necessitating movements of all records in the partially ordered list
down by one position. But whenever a record is encountered whose key is larger than that of
the last one in the partially ordered list, it merely needs to be appended to the list. Insertion sort
is done using the same list by letting the partially sorted list at the top of the combined
sequences gradually displace the diminishing list of the unsorted records stored directly
underneath.

Procedure InsertionSort(varA: list;n:integer);


{ sorts the n numbers of A, where type list = array[1.. limit]}
Var I,j,k,t,: integer;
Begin
For i:= 2 to n do
If A[i] < A[1] then
Begin
t:=A[i];
A[i]=A[1];
A[1]:=t;
End
For j:=1 to n-1 do
Begin
T:=A[j+1];
K:=j;
While A[k] >t do
Begin
A[k+1]:=A[k];
K:=k-1;
End;
A[k+1]:=t
End
end

d) Quick Sort
This is a fast sorting algorithm that sorts a list of n elements in O(nlogn) time. The method is
used as follows. One element is chosen as the partitioning element (central value). The
elements are partitioned into two sub list. Exchanges are performed so that all the elements to
one side are smaller than or equal to it and all the elements on the other side are greater the or
equal to it.(One contains the elements that are smaller than the partitioning element and the
other contains element larger than the partitioning element.). This should produce two lists of

10
equal length. Each of this is partially sorted in a similar way. In turn each of the four lists are
sorted in similar way and so on. It is sometimes referred to as partition exchange sort
Example
Program quicksort(input,output);
Const max=1001;
Var
A:array[1..max] of integer;
I:=integer;
N: integer;

Procedure quicksort(l,r:integer);
Var I, j, piv,t:integer;
Begin
If l<r then
Begin
I:=l+1;
J:=r;
Piv:=A[l];
Repeat
While A[i] <=piv do
I:=i+1;
While A[i] > piv do
J:=j-1;
If i<j then {exchange items pointed to by I
and j}
begin
t:=A[i];
A[i]:=a[j];
A[j]:=t;
End;
Until i>j;
[now two final replacements finish a partition]
A[l]:=A[j];
A[j]:=piv;
Quicksort(l,j-1);
Quicksort(j+1,r);
End;
End;
Begin
Write(‘Enter number of integers to be sorted’);
Readln(n);
For i:= 1 to n do
Read(a[i]);
A[n+1]:=maxint;
Quicksort(1;n)
For i:= 1 to n do

11
Write(A[i]:5);
Writeln;
End.

e) Merge Sort
Merging is an information processing technique similar to that of sorting that makes no sense
except when applied to two (or more) lits that are already separately in order. To merge such
lists then means to intersperse their elements to form one overall output liost that is entirely in
order. The merging algorithm can be stated in pseudocode as:
While{still more unmerged items in either list} do
Begin
If A is empty take the next item from B, else
If B is empty take the next item from A, else
Take the smaller of the two at the heads of list A and B
End;
In the course of being merged, each number in each list is processed only once. This means
that the running time needed to merge two lists of size m and n will be proportional to m+n.

Program merge(input,output);
{program that reads in two lists ordered numbers A and B and merges
them into C}
Const al=7;
Bl=9;
Cl=16;
Var A: array[1..al] of real;
B: array[1..bl] of real;
C: array[1..cl] of real;
Begin
For i=:= 1 to al do
Read(A[i]);
For j:=1 to bl do
Read(B[j]);
I:=1; j:=1; k:=1;
While (i<=al) and (j<bl) do
If A[i] <B[j] then
Begin
C[k]:= A[i];
I:=i+1;
K:=k+1;
End
Else
begin
C[k]:= B[j];
J:=j+1;
K:=k+1;

12
End;
While i<=al do
Begin
C[k] :=a[i];
I:=i+1;
K:=k+1;
End;
While j<=bl do
Begin
C[k] :=a[i];
j:=j+1;
K:=k+1;
End;

Writeln(‘ Output of list A’);


For i:= 1 al do
Write(A[i]:6:0);
Writeln(‘ Output of list B’);
For i:= 1 bl do
Write(B[i]:6:0);

Writeln(‘ Output of list C’);


For i:= 1 cl do
Write(C[i]:6:0);
End.

f) Shell Sort
This is a sorting algorithm resembles the bubble sort algorithm. The only difference between
them I that in this method successive elements are not compared and exchanged instead,
elements at a distance d are compared and exchanged if the second is smaller than the first.
The initial value of d is in n/2 location where n is the number of elements in the list. After one
iteration is over the value of d is reduces by half. This is continued until the list is sorted. The
sorting order decided by the user is encoded in the variable order.
Example
See sample programs

SEARCHING
Searching for an element in a list is the process of checking if a specified element is present in
the list and determining the location of the desired element. There are mainly two types of
searching algorithm namely
a) Linear Search
b) Binary Search

13
a)Linear Search
Is a searching technique also known as sequential search algorithm, given a list the elements
are scanned from the first one till either the required element is found or the list is exhausted.
The elements do not have to be in any specific order. The advantage of this method is its
simplicity however the method is inefficient when the number of elements is large.
Example
See sample programs

b) Binary Search
Binary search algorithm is used to search for an element in a sorted list. The search is
conducted as follows. The value of the element in the middle of the list is compared with the
value of the element to be searched for. If the middle element is smaller, them the desired
element has to be in lower half of the list. If the middle element is larger, the desired element
has to be in the upper half of its present. The number of elements to be searched is reduced by
half in every iteration.
Example
See sample programs

DATA STRUCTURES

(a) Sets
In pascal asset is a collection of ordered data items that are all of the same type. Thus a set
may be a collection of integers or characters or enumerated data items. In order to utilize the
set concept, we must first define a set type. We can then declare set type variables whose
individual values are elements of that set type.

Defining a Set Type


We begin by associating a group of ordered simple, simple data items with a data type using
TYPE defining, as we have done earlier. This data type will be known as the base type. We
can therefore establish the base type as

TYPE base type =(data item1, data item 2, . . . ,data item n)


Or
TYPE base type= first data item .. last data item.

The set type that we wish to define is then introduced in terms of the base type i.e.;

Set type = SET Of base type

Thus, the set type will refer to the same collection of data items sat the base type
Once a set has been defined we can declare a set-type variable in the following manner
VAR set name: set type
Or if several different set-type variables are desired

14
VAR set name 1, set name 2, . . ., set name n: set type.
Examples 1
TYPE sizes=(small,medium,large);
Shirtsizes= SET Of sizes;
VAR shortsleeve, longsleeve: shirtsizes;

In this example is the base type; consisting of the enumerated data items small, medium and
large. The set type is shirtsizes. Note that shirtsizes is defined in terms of the base type sizes.
Finally, shortsleeve and longsleeve are set type variables of type shirtsizes.

Examples 2
TYPE sizes=(small,medium,large);
Shirtsizes, dresssizes= SET Of sizes;
VAR shortsleeve, longsleeve: shirtsizes;
Shorthem, lonthem : dresssizes;

We can also define asset type in terms of a standard, ordered simple type (e.g. integer or char)
or subrange of a standard, ordered simple type. In such situations the standard data type or its
subrange becomes the base.
Examples 3
TYPE numbers = SET OF integer;
TYPE digits = SET OF 0..9;
TYPE lowercase = SET OF ‘a’..’z’;

Constructing a Set
A set can consist of any number of elements from associated base set. The set is constructed by
writing the individual elements consecutively, enclosed in square brakets and separated by
commas. Thus an individual set will appear as
[set element 1, set element 3, . . . . set element n]
The included elements are known as the members of the set. A set can consists of only one
element, and it is also possible to construct a set that does not contain any element. This is
known as an empty (or null) set. It is written as [].
Example

[small, medium, large]


[medium, large]
[small, large]
[medium]
[]

If some of the set members are consecutive set elements they may be represented as subrange
First consecutive element . . last consecutive element

TYPE sizes=(small,medium,large);

15
Shirtsizes = SET Of sizes;
VAR shirt, blouse: sizes;

[small . . large]
[shirt]
[shirt,blouse]
[small, medium, large]

Asset element may not be included in a set more than once. It is possible, however that a single
element will indirectly (and perhaps unintentionally) be specified two or more times,
particularly if the set specification includes both explicit set elements and variables( A variable
may represent a set element that has already been specified thus resulting in unwanted
duplication.) in such situations the repeated specifications will be ignored.
Once a set has been constructed, it can be assigned to asset type variables. This is
accomplished in the usual manner, by writing
Variable name: = [set element 1, set element 2 … set element n]

It should be understood that the set appearing on the right hand side is regarded as a single-
valued data item. This data item must be of the same set type as the variable to which it is
assigned.

Program sample;
TYPE sizes=(small,medium,large);
Shirtsizes, = SET OF sizes;
VAR shortsleeve, longsleeve: shirtsizes;

Begin
……….
Shortsleeve:=[small,large];
………
Longsleeve:=[small,medium,large];
…………
End.

Operations with Sets


There are three difference operations that can be carried out with sets, each of which results in
the creation of a new set. We refer to the resultant of this operation (i.e., the newly created
sets) as the union, the intersection and the set difference of the original two sets, respectively.
Each set operation requires two operands(i.e, two set) of the same type. The resultant will then
be of the same type as the operands. The union of the two sets is a new set that contains all the
members of the original two sets. The + operator is used to indicate this operation as illustrated
below

Program sample;
TYPE sizes=(small,medium,large);

16
Shirtsizes, = SET OF sizes;
VAR shortsleeve, longsleeve: shirtsizes;

Begin
……….
Shortsleeve:=[small]+[large];
………
Longsleeve:=[small,medium]+[small,large];
…………
End.
The intersection of two sets is set whose members are common to both of the original sets. we
use the operator * to denote this operation.

Program sample;
TYPE sizes=(small,medium,large);
Shirtsizes, = SET OF sizes;
VAR shortsleeve, longsleeve: shirtsizes;

Begin
……….
Shortsleeve:=[small, medium]*[medium ,large];
………
Longsleeve:=[small]+[medium, large];
…………
End.
The set difference of two sets is set whose members are in the first set but not in the second.
This operation is denoted by the operator – as in the example below.
Program sample;
TYPE sizes=(small,medium,large);
Shirtsizes, = SET OF sizes;
VAR shortsleeve, longsleeve: shirtsizes;

Begin
……….
Shortsleeve:=[small, medium]-[small ,large];
………
Longsleeve:=[small, medium, large]- [medium] ;
…………
End.

(b) Stacks
A stack is an abstract data type consisting of sequence of items, in which the items are added
and removed from one end only. Another way of describing a stack is that the last item put in
the stack will be the first one to be taken out of the stack. Consequently, a stack is referred to

17
as “Last In First Out (LIFO)”, structure. For example if the integers 10, 20, 30, 40 and 50 are
put in a stack, they would come off the stack in the order 50, 40, 30, 20, and 10.

Operations of stack
Two main operations are involved in the use of stack. The operations of adding an item to the
stack is known as “pushing” the item on to the stack and the operation opposite pushing on to
the stack is a called “popping” the stack.
Push()
Pop()
Push() procedure is used to add new elements to the top of the stack where as the pop()
procedure is used to remove an element from the stack. Initially an empty stack must be
created whenever there is attempt to push an element into a stack, it must be checked whether
any space is there to accommodate new elements in the stack or not. While attempting to user
popping operation it must be checked whether any element is there which is to be popped out.
For example
Stack operation contents
Push(a) a
Push(b) ba
Push(c) cba
Push(d) dcba
Pop() cba d is removed
Pop() ba c is removed
Push(e) eba

A simple stack can be created using an array. Stack elements are integers but they can be float,
char, structures etc.

Algorithm for push() operation


The push() is an operation for storing an item in a stack. If s is attack and x is and item to be
pushed on to s, we will use push(s,x) to denote the process by which thee value denoted by x is
added to the top of the stack s. before pushing an item into a stack, it is essential to check
whether enough space is there to accommodate the item. Otherwise, an appropriate error
message ,stack full’ will be displayed.
The following procedure shows how to realize push() operation for a stack:

procedure push(var s:stack; var spointer:integer; item,max:intger);


begin
if spointer < max then
begin
spointer:=spoiter+1;
s[spointer]:=item;
end
else

18
writeln(‘stack full’);
end;
Algorithm for Pop() Operation

The pop() is an operation in which the top most item of a stack is to be removed or delete.
Popping the stack reference the value from the top of the stack. If s is a stack and v is a
variable of the type of element in the stack, pop(s,v) will put the value on the top of the stack s
in the variable v. pop also makes the stack one item shorter. Before one attempts to pop() an
item from the stack, it is essential to check whether any item is stored in the stack. If not, he
stack is empty and nothing can be popped ands hence an error message ‘stack is empty’ will be
displayed.
The following procedure shows how to realize pop() operation for a stack:

procedure pop(var s:stack; var item, spointer:integer);


begin
if spointer >0 then
begin
item:=s[spointer];
spointer:=spoiter-1;
end
else
writeln(‘stack empty’);
end;

To type aprogram

(c) Queues
A queue is sequence of data items for which additions and deletions are possible only at an end
of the sequence. The difference between a queue and stack is that the addition and deletion of
items to a queue are at opposite ends whereas the addition and deletion of items in stack are
done at the same end.
Stacks are useful in problems that reverse the order of items and queues are useful in problems
that preserve the order of the items. A queue is an ordered group of items in which new
elements are added at one end called the rear and elements are removed at the other end called
the front. Queues are also known as FIFO-, First In First Out’ structure. The term front will
denote the end of the queue from which items are removed and rear will denote the end at
which items are added.

Operations on Queue
The main operations on aqueue are additions of items of the queue and removal (deletiond) of
items from the queue

qstore()
qdelete()

19
The qstore() procedure is used to add new elements to the queue while qdelete() procedure is
used to remove an item from the queue.

For example
Stack operation contents
qstore(a) a
qstore(b) ba
qstore(c) cba
qstore(d) dcba
qdelete() dcb a is removed
qdelete() dc b is removed
qstore(e) edc

Algorithm for qstore()


The qstore() is an operation in which an item is stored in the queue. The end to which
additions are made is the rear of the queue. Before one attempts to store an item in to a queue,
it essential to check whether enough space is there to accommodate the item in the queue or
not. If there is no space in the queue an appropriate error message ‘queue full’ is displayed.

The following procedure shows how to realize qstore() operation in a queue

procedure qstore(var q:queue; var rear: integer; item,


max, front :integer);
begin
rear:=rear+1;
if rear >max then
rear:=1;
if front<> rear then
q[rear]:=item
else
begin
writeln(‘queue is full’);
rear:=rear-1;
if rear =0 then
rear:=max;
end;

end;

Algorithm for qdelete()


The qdelete() is an operation in which an item is removed from a queue. Items are removed
from the end, opposite to the end used for addition. The end from which removals are made is
the front of the queue. Before one attempts to delete an item from the queue, it is essential to

20
check whether any item has been stored or not. If there is no item in the queue, it is an error to
use the qdelete() procedure and appropriate error message ‘queue empty’ will be displayed
The following procedure shows how to realize qdelete () operation in a queue

procedure qstore(var q:queue; var item, front: integer;


max, rear :integer);
begin
if front <> rear then
begin
front:=front+1;
if front > max then
front:=1;
item:= q[front];
writeln(‘value =’,item)
end
else
writeln(‘queue empty);
end;

(d) Linked Lists

Linked lists like stacks and queues are linear data structures in which the items are stored and
retrieved linearly in an organized manner like one item after another. A linked list is like a
chain of data items connected by pointers and each item contains a pointer to the address of the
next item.
There are several different kinds of linked structures
a) linear linked lists :In which the components are all linked together in some sequential
manner,
b) Linked list with multiple Pointers: Permitting forward and backward traversal thro’ the
list.
c) Circular list: Linear list having no beginning and no ending.
d) Trees: in which the components are arranged in a hierarchical structure.

For example the following program segment illustrates how a linear linked list is declared and
connected with another list with the aid of pointer.
type
pointer=^list;
list=record
data:integer;
next:pointer;
end
var
a,b,c:pointer;
begin
a^.data:=10;

21
b^.data:=20;
c^.data:=30;
a^.next:=b
b^.next:=c;
c^.next:=nil;
end.

The graphical representation of the above structure is

a b c

10 20 30 nil
next next next
Linked lists are used for example in construction of compilers, operating systems and database
management systems.
Example of aprogram that demonstrates how a simple linear linked list is working
program selfglist(input,output);
type
pointer=^list;
list=record
data:integer;
next:pointer;
end
var
a,b,c:pointer;
x,y,,z:integer;
begin
a^.data:=10;
b^.data:=20;
c^.data:=30;
a^.next:=b
b^.next:=c;
c^.next:=nil;
writeln(‘contents of the lits’);
write(‘value of ‘);
x:=a^data;
writeln(‘a = ‘,x);
writeln(‘a is linked to b’);
y:=a^.next^.data;
writeln(‘b = ‘,y);
writeln(‘b is linked to c’);
z:=a^.next^.data;
writeln(‘c = ‘,z);
a^.next^.next^.next:=nil;

22
end.

Double linked Lists


A linked list that has two links in each of its nodes, with one link pointing to the preceding
node and the other pointing to the succeeding node is called a double linked list. In other
words a double linked list in a data structure has two pointer elements; one pointing to the next
element and the other pointer pointing to the previous element and can traverse the list in
either direction.
The declaration of a double linked list structure is:

type
doubleptr=^node
node= record
llink:doubleptr;
value: integer;
rlink:doubleptr;
var
head,tail:doubleptr;

The graphical representation of the double linked list is shown below:

Data = 10

10

Prev next
Data = 20

20

Prev next
Data = 30

30

Prev next

(e) Binary trees


Data structures such as stacks, queues and linked lists are linear organization of data in which
items or components are arranged sequentially, one object after another. On the other hand,
components or items are arranged in hierarchical order then it is called a tree. Tree is more
flexible abstract data type than linear types.

23
A tree has a finite set of elements called nodes. A tree has a unique node called root. A binary
tree ia a tree whose elements have two nodes such as a left node and a right node. Each left
node contains a number less than the value in the preceding node. Each right node value is
greater than the value in the preceding node. Anode with no branch is called a leaf.
The advantage of a binary tree is that items can be placed in the tree in a sorted manner. Thus
the processes of inserting a node, deleting anode, searching for a node and retrieving
information can be accomplished in a more efficient manner than with a linear linked list. The
node above a given node in a tree is called a parent and the node below a given node in a tree
is called a child. The root is the unique node of a tree without a parent. The node with no child
is called a leaf. The link from a parent node to a child is called a branch. The tree that is part of
another tree is called a subtree.
The declaration of a binary tree is:
type
pointer=^node;
node=record
data:integer;
left:pointer;
right: pointer;
end;

Binary Tree Traversal


A binary tree is built and searched by moving downwards thro’ the tree node by node, until an
empty child is reached or anode with a specific item is found. There are several ways to visit
elements of a binary tree. This include inoder, preorder and postorder.

(i) inorder
Inorder traversal is a process of a binary tree in which a node is visited between the traversal
of the node’s left sub tree and the traversal of the node’s right sub-tree.
Example

B C

Diagram 1

24
In the example in ther inrder tree traverse, first the left sub-tree of the root is traversed(B). the
root is then visited(A). then the right sub tree is visited(C).

The following recursive procedure prints the contents of the binary tree in the inorder traversal
method.

Procedure inorder(ptr1:pointer);
(*inorder binary tree traverse*)
Begin
If ptr1<> nil then
Begin
Inorder(ptr1^.left);
Write(ptr1^.data:7);
Inorder(ptr1^.right);
End;
End;

(b) Preorder
In a preorder tree traverse a node is visited before its sub tree are traversed. It first visits the
root node(A), then traverse the left sub tree(B) and then the right sub tree(C).

The following recursive procedure prints the contents of the binary tree in the preorder
traversal method.

Procedure preorder(ptr1:pointer);
(*preorder binary tree traverse*)

Begin
If ptr1<> nil then
Begin
Write(ptr1^.data:7);
preorder(ptr1^.left);
preorder(ptr1^.right);
End;
End;

(c) postorder
When a postorder traversal on a tree is performed, both the left and the right sub tress are
traversed before the root node is visited. Using the previous diagram 1 the order will be B C
A
The following recursive procedure prints the contents of the binary tree in the postorder
traversal method.

Procedure postorder(ptr1:pointer);
(*postorder binary tree traverse*)

25
Begin
If ptr1<> nil then
Begin
postorder(ptr1^.left);
postorder(ptr1^.right);
Write(ptr1^.data:7);
End;
End;
Example
A program to create a binary tree and to display the contents of the tree using the inorder tree
traversal methods

program binary(input,output);
type
pointer=^node;
node=record
data:integer;
left:pointer;
right: pointer;
end;
var root:pointer;
item:integer;
i,n:integer;

procedure inorder(ptr1:pointer);
(*inorder binary tree traverse*)
begin
if ptr1<> nil then
begin
inorder(ptr1^.left);
write(ptr1^.data:7);
inorder(ptr1^.right);
end;
end;

procedure buildtree(var bnode:pointer; value:integer);


begin
if bnode=nil then
begin
new(bnode);
bnode^.data:=value;
bnode^.left:=nil;
bnode^.right:=nil
end

26
else if value <=bnode^.data then
buildtree(bnode^.left,value)
else
buildtree(bnode^.right,value);
end;
begin (*main program*)
root:=nil;
writeln('homany elements ?');
readln(n);
i:=1;
while i<=n do
begin
writeln('enter a number');
readln(item);
buildtree(root,item);
i:=i+1;
end;
writeln;
writeln('output from the binary tree');
write('using inoreder algorithm');
inorder(root);
end.

27

You might also like