Vous êtes sur la page 1sur 59

INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

Concept of Algorithm
-It is a set of finite rules that precisely define a sequence of operations. However an algorithm can be in the form of
1 flow chart
2 Pseudocode
3 The actual program or code

Concept of data structure


-It is the collection and organization of related data items in the computers memory.
-Matrices are examples of data structure in that the data has a positional relationship
-The study of data structures is a fundamental part of the study of Algorithms and programs just as numbers can be represented in
several different systems so can a set of related data be fitted into many different data structures.

When a programmer creates an algorithm to solve a problem he also creates a data structure that is manipulated by the algorithm.

SCHEMATIC REPRESENTATION OF DATA STRUCTURES

DATA STRUCTURE

LINEAR NON-LINEAR

SEQUANTIAL STATIC DYNAMIC STATIC DYNAMIC


Data files Array, sets, stack Linked list, stack Tree graphs Tree graphs

Operations with data structures

1 Browsing
it is the process of displaying each and every record in a data structure.
2 Searching
It is the localization of a specific record for specific information.
3 Insertion
It is the addition of 1 or more records into a data structure.
4 Deletion
It is the removal of one or more records from a data structure
5 Sorting
It is the arrangement of records to suite a specific order.
6 Merging
It is the joining of 2 structure of the same type to from 1 single structure

1 Array of records
Type
Nd2=record
Name: string;
Age: byte;
Assuming the above declaration
1 Building an array
a) Open a loop
-With a current record
-Accept name
-Accept age
-Move to the next record
-Repeat the above operations limited to the last record
b) Close cycle/loop
2 Browsing through an array
a) Open a loop/cycles
-With current record
-Write name
-Write age
-Move to next record
-Repeat the above operations limited to the last records
b) Close cycle/loop
3 Searching within an array

Two methods can be used


a) Sequential searching
-It refers to the extraction of a required record from an array processing each record in the order in which they
were entered or accepted.
b) Binary searching
-It is the process of comparing the wanted item with the element situated at the centered position of the list and
repeatedly rejecting the unwanted half.
ALGORITHM FOR SEQUENTIAL SEARCHING
-Given a value item to be searched for in an array called data with n elements the algorithm is as follows:
p:=0;
For I: = 1 to n do
If data [I]=item then p:=I;
If p<>0 then
Writeln (item fo47 444444444444444
R4444444444j444444j444444j444444j4

1. third array [I] := first array[I] else third array := second array [ I- x]
2. Close cycle
3. End

Sets

Those are a collection of objects of the same nature


E.g. { 1; 3; 5; 7; 9} set of odd integers
{ } = emp set or null set

Declaration of sets in Pascal


Type
Numbers = set of 1..10;
Var
Even, odd: numbers;
Or
Type
Colors =(red, orange , yellow);
Colourset= set of colors
Var
Rainbow, paint: colourset

Relational operators (><=)


Sets may be compared using sets relational operators
1. Inequality set 1 = set 2
2. Inequality set 1 < > set 2 subset- set 1 < set 2
3. Superset - set 1 > set 2
4. Proper subset set 1 < = set 2
5. Proper superset set > = set 2
6. Set membership - object

There are three basic operations with sets i.e.


1. Union
2. Intersection
3. Difference

Union {+)
It is a set that contains all the objects from both sets.
A= [1, 5, 7, 9]
B= [10, 18, 20]

Therefore the union of A and B is a set C with all elements from A and B
C = [1, 5, 7, 9, 10, 18, 20]

Intersection (*)

It is a set consisting of elements that are common in both sets.


A = [1, 2, 3, 4]
B = [0, 2, 3, 7]
Therefore the intersection of A and
C = [2; 3]
Difference ( - )
-It is a set consisting of all elements that are not elements of A and B.
A = [1, 2, 4, 5]
B = [1, 5]
The difference of A and B is a set C = [2, 4]

ALGORITHIM TO CONSTRUCT A SET


1. Initialize S to the empty set
2. While there is more data do the following
a) Read a value for a variable x whose type is that of the base type of S { set of numbers base type}
b) Add x to S using the union operation { s := s + [x]; }
3. End.

ALGORITHIM TO DISPLAY A SET


1. Let x be a variable of s and initialize x to be the first element of the base type.
2. While s < > [ ]do the following
a) If x is not in s replace x with its successor
b) Display x
c) Remove x from s using the difference operation {s:= s [x]}
Set s is destroyed since it is reduced to be empty set . if the set to be displayed is reserved it should be first copied to a temporary set.

Q1 Write a menu driven program that performs the following operations:


a) Build two sets T and S of integers
b) Display the elements of the two sets
c) Determine the union of the two sets
d) Determine the intersection of the two sets
e) Determine the difference of the two sets

DATA FILES
A text file was created either by using an Editor or the output director to secondary storage from the program.
-A program can only create a file of records.
-Files of records make programming easy and efficient and access to items is rapid.

-Procedures used with data files


1) Assign ( variable , Name of file )
it is used to assign file name to the variable
it should never be used with open files
2) Rewrite (f)
- Prepares a file for writing
3) Reset (f) prepares a file for reading
4) Append (f) prepares a file for appending records, if also records with text files.
5) Read (f, record) used to read records to the file
6) Write (f, record) used to write record to the file
7) Close (f)
8) Trancate (f) used to cut a file

Functions used with data files.


1. EOF (f) it returns the state at the end of the file.
2. SEEK (f) it takes the caser to the end of the file.
3. SEEK (f.n) it takes the caser to pos n
4. FILESIZE (f) it returns the size of the file

OPERATIONS WITH DATA FILES


1) Creating a data file
2) Retrieving records
3) Deleting records
4) Inserting records
5) Editing or modifying records
6) Appending records
Assuming the following declarations

Type
Studone = record
Name: string [10];
Age : Byte
End;
Fstud = file of student;
Var
F : fstud;

CREATING A DATA FILE

Procedure create file

Var
I, n : integer;
Data: structure;
Begin
Assign (f, ND2.DAT);
REWRITE (f);
Writeln (enter number of student);
Readln (n);
For I: = 1 to n do
Readln (data. name);
Readln (data. age);
Write (f, data);
End;

Retrieving records from a file


Procedure retrieve
Var
Data: student;
Begin
Assign (f, Nd2.dat);
While not EOF do
Begin
Read (f, data);
Writeln (data. name);
Writeln (data. age);
End;
Close (f);
End;

EDITING RECORDS

Procedure Editrecords
Var
N: integer
Data: student
Begin
Writeln (enter records number to be edited);
Readln (n);
Assign (f;ND2.Dat);
Reset (f);
SEEK (f, n 1);
Readln (data. name);
Readln (data. age);
Write (f , data) ;
Close (f);
End;
Appending Records

Procedure append;
Var
N : integer;
Data : student;
Begin
Assign (f, nd2.dat);
Reset {f};
N := filesize (f);
SEEK (f, n);
Readln (data.name);
Readln (data.age)
Write (f.data);
Close (f);
End;

DELETING A RECORD
Procedure deleterec;
Var
I, n : integer;
Data : integer;
Begin
Write (enter record number to be deleted);
Readln (n);
Assign (f, nd2.data);
Reset(f);
SEEK(f,n);
I := n 1
While not EOF (f) do
Begin
Read (f, data);
SEEK (f, I);
Write (f, data);
Inc ( I );
SEEK ( f , I + 1);
End;
Seek (f, filesize (f) 1);
Trancate (f);
Close (f)
End;

INSERTING A RECORD
Procedure insert;
Var
Data : student;
Pos, I : integer;
Begin
Writeln (enter position);
Readln (pos);
Assign ( f , nd2.dat);
Reset ( f);
SEEK (f, filesize (f) 1);
For I = filesize( f) down to pos 1 do
Begin
Read ( f, data );
SEEK ( f, I );
Write (f, data) ;
SEEK (f, I- z);
End;
SEEK (f, pos 1);
Readln ( data.name);
Readln (data.age);
Close (f);
End;

POINTERS IN PASCAL AND DYNAMIC DATA ALLOCATION

- Pascal divides the computers memory into 4 parts


STACK HIGH MEMORY
-------------- Dynamic storage, which consists of all memory, left over after the code and data segments
HEAP have been allocated

DATA Global variable


SEGMENT
CODE LOW MEMORY
SEGMENT Code Segment holds constants and executable code

- Variables that are declared in procedures and functions are stored in the stack and after use they are discarded.
- The heap allows efficient use of memory whereby you can create and discard variables .-The heap uses dynamic data types such as
pointers
-Pointer variables are dynamic because they can be created and disposed during execution of the program.
-If Pascal detects a stack heap collision it generates a runtime error

Creation of stack pointer.

NEW (p)- It assigns an address on the heap to a pointer P.


DISPOSE (p)- Effectively takes the variable P off the heap allowing memory to be used for other variables.
Linked List
-These are an alternative to implement lists whereby we use pointers.
-There are 2 types of lists namely single linked lists and double linked list.

Single linked list


-Operations with single linked lists include the following
1) Creating a single linked list
2) Listing record contents of single linked list
3) Eliminating an element given position
4) Inserting an element given position
5) Appending an element
6) Eliminating all elements

Assuming the following declarations:

Type
Pstudent = ^studentrec
Studentrec = Record
Name: string [10];
Age: Byte;
Next: pstudent;
End;
Var
Pfirst, ptemp, pactual: pstudent;
ALGORITHIM FOR CREATING A SIMPLE LINKED LIST
1. Pfirst should point to nil.
2. Create a node using pactual, enter data and give it direction nil.
3. If Pfirst = nil then Begin
Pfirst := Pactual
Ptemp := Pactual
End
Else
Ptemp^.next := Pactual;
Ptemp := Pactual;
4. Repeat step 2 and 3 until a given condition .
5. End.

ACTUAL CODE

Procedure createlist;
Var
Resp: char;
Begin
Pfirst := nil;
Repeat
New (pactual);
Readln (pactual^.name);
Readln (pactual^.age);
Pactaul^.next := nil;
If Pfirts = nil then
Begin
Pfirst := pactual;
Ptemp := pactual;
End;
Else
Ptemp^.next := pactual;
Ptemp := pactual;
Writeln (Do you want to continue y/n:);
Resp := upcase (readkey);
Until resp = N;
End;

ALGORITHIM FOR LISTING RECORD CONTENTS


1. Locate the first node using variable temp.
2. Repeat up to the last node.
- Read contents of record and display them
- Move to next record.
3. End;

ACTUAL CODE
Procedure listrecords;
Begin
Ptemp := pfirst;
While ptemp <> nil do
Begin
Writeln (ptemp^.name);
Writeln (ptemp^.age);
Ptemp := ptemp^.next;
End;
End;

ELIMINATING AN ELEMENT GIVEN A POSITON

Algorithm
1. Enter the position to eliminate element.
2. Locate the first node.
3. If position = 1 then Begin
- Move the 1st pointer to the 2nd node
- Dispose the 1st node
- Exit.
Else
Repeat for I := 1 to pos 2
Move the temporary pointer to the next position.
4. Move the actual pointer to the next position of the temporary node.
5. Point the next of the temporary pointer to its next of next node.
6. Dispose the actual pointer.
7. End.

ACTUAL CODE
Pocedure eliminate;
Var
Pos, I : integer;
Begin
Readln (pos);
Ptemp := pfirst;
If pos = 1 then
Begin
Ptemp:= ptemp^.next;
Dispose (ptemp);
Exit;
End
Else
Begin
For I := 1 to pos 2 do
Ptemp := ptemp^.next;
Pactual := ptemp^.next;
Ptemp^.next := pactual^.next
Dispose
End;
End;

ALGORITHIM FOR INSERTION


1. Create node and enter data using Pactual and give it direction nil.
2. Enter position to insert.
3. Locate the 1st node .
4. If position = 1 then Begin
Pactual^.next := Pfirst;
Pfirst := pactual;
Exit
End
Else report
For I := 1 to pos 1
Move the temporary pointer to its next.
5. Point pactual to the next of ptemp.
6. Point ptemp to pactual.
7. End;

1 Type
nodetype = record
info : infotype;
Next : ^Nodetype
End;
Var
List, prt : ^Nodetype

2 Type
Listtype = pointertype;
Var
List : Listtype;
Per : Pointertype;

List Vs List^

List or pfirst or pactual are all pointer variables or addresses.


List, pfirst^ - refers to the node of the linked list pointed to by the pointer variables. It is the data is pointed to.

Procedure insert;
Var
I,pos :integer;
Begin
New (pactual);
Readln (pactual^.age);
Readln (pactual^.name);
Pactual^.next:=nil;
Readln (pos);
Ptemp := pfirst;
If pos = 1 then begin
Pactual^. := pfirst;
Pfirst : pactual;
End;
Else
Begin
For I := 1 to pos 2 do
Ptemp := ptemp^.next;
Pactual^.next := ptemp^.next;
Ptemp^.next := pactual;
End;
End;
PROCEDURE FOR APPENDING
Algorithm Append
1. Create a node using pactual, enter data and give it direction nil.
2. Locate the first node using ptemp.
3. While ptemp^.next < > nil
-move ptemp to its next node
4. Point ptemp to pactual.
5. End.

Procedure Append_record{add record};


Begin
New (pactual);
Readln (pactual^.name);
Readln (pactual^.age);
Pactual^.next := nil;
Ptemp := pfirst;
While ptemp^.next <> nil do
Ptemp := ptemp^.next;
Ptemp^.next := pactual;
End;

Algorithm for deleting all nodes


1. Locate the first node using ptemp.
2. While ptemp < > nil
Move pfrist to next of ptemp
Dispose ptemp
Move ptemp to first
3 End;
Procedure delete; {all nodes}
Begin
Ptemp := pfirst;
While ptemp <> to nil do
Begin
Pfisrt:= ptemp^.next;
Dispose (ptemp);
Ptemp:= pfisrt;
End;
End;

Algorithm for sorting


Procedure sort;
Begin
Ptemp := pfirst;
While ptemp < > nil do
Pactual := ptemp^.next ;
While pactual < > nil do
Begin
If ptemp^.name > pactual^.name then
Begin
New (pauxlary);
Pauxilary^.name := ptemp^.name;
Pauxilary^.age := ptemp^.age;
Ptemp^.name := pactual^.name;
Ptemp^.age := pactual^.age;
Pactual^.name := pauxilary^.name;
Pactual^.age := paxulary^.age;
Dispose (pauxilary);
End;
Pactual := pactual^.next;
End;
Ptemp:= ptemp^.next;
End;

DOUBLE LINKED LIST

-These are lists that can be transversed forward as well as backward in such a list, each node contains 2 pointers, 1 to its successor and
another to its predecessor.

Assuming the following declarations.

Type
Pstudent = ^studentrec
Studentrec= record
Name : string
Before,next:pstudent;
End;
Var
Pfirst, pactual :pstudent;
Procedure createlist;
Begin
Pfirst := nil;
Pactual := nil;
Ptemp := nil;
Repeat
New (pactual);
Readln(pactual^.name);
Readln(pactual^.age);
Pactual^.next := nil;
Pactual^.before := ptemp;
If pfirst is nil then
Pfirst := pactual;
If ptemp < > nil then
Ptemp^.next := pactual;
Ptemp:= pactual;
Writeln (Do you want to continue Y/N);
Resp := upcase (readkey);
Until resp = N;
End;

Procedure Traverse_forward;
Begin
Ptemp := pfirst;
While ptemp < > nil do
Begin
Writeln (ptemp^.name);
Writeln (ptemp^.age);
Ptemp := ptemp^.next;
End;

Procedure traversebackward;
Begin
Ptemp := pactual;
While ptemp < > nil do
Begin
Writeln (ptemp^.name);
Writeln (ptemp^.age);
Ptemp := ptemp^.before;
End;
End;
Procedure Delete;
Var
I, pos : integer;
Begin
Readln (pos);
Ptemp := pfirst;
If pos = 1 then
Begin
Pfirst := ptemp^.next;
Pfirst^.before := nil;
Dispose (ptemp);
Exit;
End;
Else
Begin
For I := 1 to pos -1 do
Ptemp:= ptemp^.next;
End;
Then
Ptemp^.next^.before := ptemp^.before;
Ptemp^.before^.next := ptemp^.next;
Dispose(ptemp);
End;

Procedure insert;
Var
I, pos :integer;
Begin
New (pactual);
Readln(pactual^.name);
Readln(pactual^.age);
Pactual^.next := nil;
Pactual^.before := nil;
Readln(pos);
Ptemp := pfirst;
If pos = 1 then
Begin
Pactual^.next := pfirst;
Pfirst^.before := pactual;
Pfirst := pactual;
End;
Else
Begin
For I := 1 to pos -2 do
Ptemp:= ptemp^.next;
End;
Pactual^.next := ptemp^.next;
Pactual^.before := ptemp;
Ptemp^.next^.before := pactual;
Ptemp^.next := pactual;
End;

STACK DATA STRUCTURE


- Is a special type of a list in which insertions and removal of elements are done at one end called the top.
- It conforms to the LIFO principle (last in first out) i.e. the last element to be inserted will be the first element to be removed.

Diagrammatic representation

DON TOP
MEG
JOHN
FELIX
GODIE BOTTOM

PUSH
It is the insertion of new elements on to the stack.

POP
The removal or deletion of elements from the stack.

TOP OF STACK
Is the one end of the stack which is most accessible were pop and push operations can be done.

BOTTOM OF STACK
It is the other end of the stack that is least accessible.

UNDERFLOW
The result of an illegal attempt to push an element into an already full stack.
NB Overflow only occurs when the stack structure was implemented statically.

Given a static structure (s) consisting of (n) cells and a variable top denoting the file top cell in the stack and an element x to be
pushed on to the stack.

PUSH ALGORITHIM
1. If top 7 = N then print overflow message and exit.
2. Else set top to top + 1 (top := top + 1).
3. Set s[top] to x (s[top] := x).
4. End.

POP ALGORITHM
1. If top = 0 then print underflow message and exit.
2. Else set x to s[top] (x:= s[top]).
3. Set top to top- 1 (top := top -1).
4. End.

Implementation of stack using pointers (dynamic implementation).

Assuming the following declaration


Type
Stack =^list;
List=record;
N=integer;
Next=stack;
Procedure push(var top: stack; x :integer);
Var
Pactual : stack;
Begin
New (pactual);
Pactual^.n := x ;
Pactual^.next := Top;
Top := pactual;
End;

Function Empty (top :stack):Boolean;


Begin
If top = nil then
Empty
Else
Not empty
End;
Function pop(var top:stack ):integer;
Var
Pactual: stack;
X: integer;
Begin
If empty then
Writeln (underflow);
Else
Begin
Pactual := top;
Top:= pactual^.next;
X:=Pactual^.n;
Dispose (pactual);
Pop := x;
End;
End;

QUEUES
-It is a special list in which elements can be deleted or removed using one end called the front ant inserted at the other end called the
rear.
-It conforms to the principle FIFO. The data is processed following the sequence in which it was accepted.
-Three primitive operations on queue are defined:
1. Insertion.
2. Deletion or removal.
3. Checking contents of the queue.

Assuming the following declarations

Type
Node= ^rear;
Rear= record;
Info=integer;
Next=node;
End;
Procedure push(Var front, final: node; x:integer);
Var
Pactual:node;
Begin
New (pactual);
Pactual^.info := x;
Pactaul^.next := nil;
If front = nil then
Begin
Front := pactual;
Final := pactual;
End;
Else
Begin
Final^.next:= pactual;
Final := pactual;
End;
End;

Function Pop( var front: node) : integer;

Var
Pactual: node;
X: integer;
Begin
Pactual := front;
Front:= pactual^.next;
X := pactual^.info;
Dispose(pactual);
Pop := x;
End;

Write the push and pop algorithm for a queue that is implemented statically.

Push Algorithm
1. If rear >n then print overflow message and exit.
2. Else set rear to rear + 1.
3. Set queue [rear] to x queue[ rear] :=x ;
4. End;

Algorithm POP (Statical);


1. If front = 0 then print underflow message and exit.
2. Else set x to queue [front]
3. Set front to front 1.
4. End.

Radix Sort
- It is a method that involves sorting of elements in a file (elements being numbers) considering digits that make up the numbers.

Algorithm
1. Make sure all numbers has equal number of digits.
2. Sort the numbers considering first the least significant digits pushing them into a queue.
3. POP them from the Queue considering the FIFO principle.
4. Repeat 2 and 3 until you have considered the most significant digits e.g. sort the following list of numbers 42; 23; 74; 11; 6;
65; 57; 22
Step 1 42; 23; 74; 11; 06; 65; 57; 22
Step 2 22; 23; 74; 65; 06; 57
0 1 2 3 4 5 6 7
11 22 23 74 65 06 57
Step 3 tens 0 1 2 3 4 5 6 7 8 9
Sorted 06 11 22 23 42 57 65 74

Sort the following numbers using radix sort


1192; 1021; 2461; 372; 896; 1870; 1194; 1190; 2000
Step 1 1192 1021 2461 0372 0896 1870 1194 1190 2000
2000 2461 0372
1570 1021 1992 1194 0896
1 2 3 4 5 6 7 8 9
1870 1190 2000 2461 1021 0372 1192 1194 0896
tens 1 2 3 4 5 6 7 8 9

Merge Sorting
Algorithm
1. Open file 1 and file 2 for input and file 3 for output.
2. Read the first element x from file 1 and element y from file 2.
3. Repeat the following until either the end of either file 1 or file 2 is reached
. - If x < y 1) write x to file 3
2) Read a next x from file 1
Otherwise
1) Write y to file 3
2) Read a new value from file 2
5. If the end of file 2 was encountered copy remaining elements from file 2 to file 3
Else copy remaining elements from file 1 to file 3.

RECURSION
Given a positive integer n. n! is defined as the product of all integers between n and 1
E.g. 3! = 3 *2 *1
N! = n * n-1 * n-2 *.*1 if n > 0
O! = 1 by definition
N! =0 if n= 0

Recursion is technique whereby a procedure or function in the process of performing its tasks makes rolls to itself.
-Recursion can best be described by close example of factorial function.

Non Recursive factorial functions

Write a function that will receive as parameters integer n and computes its factorial.

Function factorial (n: integer) : integer;


Var
I, f :integer; x: integer;
Begin prod: integer;
F := 1; Begin
For I := 1 to n do prod := 1;
F:= f * I; x:= n;
Factorial := f; While x < > 0 do
End; Begin
Prod:= prod * x
X := x 1
End;
Factorial := prod;

Recursively 1 if n = 0

N! =

N * (n 1)! If n > 0

Function Factorial (n : integer) : integer;


Begin
If n = 0
Then
Factorial := 1
Else
Factorial := n * factorial (n 1)
End;

Fibonacci sequence
The numbers of a fibonnacci form an interesting sequence in which each number is equal to the sum of the two procedures .
I.e.
F1 = Fi-1 + Fi-2
Where If refers to the Ith number of fobonacci.
-the first two numbers are equal to 1 by definition
i.e.
F1 = F2 =1
E.g.
(1, 1, 2, 3, 5, 8)
Write an iterative function fibonnaci to calculate the nth fibbonacci number for a positive integer n pass as parameter.

Function Fibonacci (n: integer) : integer


Var
I, prev, current, f :integer;
Begin
Prev:= 1;
Current := 1;
F := 1;
For I :=3 to n do
Begin
F:= prev + current;
Prev := current;
Current:= f;
End;
Fibonacci := f;
End;

Recursively the nth

1 If n = 1 or n = 2

Fn

F n- 1 + f n - 2 If n > z

Function fibbonacci (n : integer ) : integer;


Begin
If (n=1) or (n=z) then
fibbonaci = 1
Else
Fibonnacci:= fibonnacci (n-1) + fibonnacci(n 2);
End,

Fibo (5) + fibo (4)

Fibo (4) + fibo (3)

Fibo (3) + fibo (2)

Fibo (2) + fibo (1)


Binary Searching
Recursive (binary search)
Function Binsearch (a:arraytype; x, low,upper:integer): integer;
Var
mid : integer;
if low > upper then
Binsearch := 0
Else
Begin
mid := (low + upper ) div 2
if x = a[mid] then
binsch := mid
else
if x < a[mid] then
binsch:=
Binsch (a, x, low. mid 1);
Else
Binsch := binsch (a, x, mid + 1, upper);
End;

Advantages of recursion
1. It is more elegant and intellectually appealing.
2. Some algorithms are naturally adapted to recursive structure thus forcing them into non recursive form does not make sense.

Disadvantages
1. Each time when a procedure or function calls itself Pascal must set-up space on the stack for temporary storage thus slows
function or procedure execution and increase danger of stack heap collision that generates a runtime error.
2. Recursive functions are difficult to understand and code.

QUICKSORT
It is based on the fact that it is faster and easier to sort the small list than one large one.
Algorithm

IF not finished
Then select a splitting value v
Split on v
Quicksort the elements less than or equal v
Quicksort the elements greater than v

Information needed - specify name of the array, its size

Procedure print (p :pointer, L, u:integer);


Var
Ptemp : pointer;
Begin
If ( l > u ) then
writeln ( error);
Exit
Else

Procedure Merge(p, q, : pointer);


Var
Ptemp, pauxilary, pactual, t, m :pointer;
Begin
Ptemp := p;
Pauxilary :=0;
T := nil;
While ptrmp < > nil or pauxilary < > nil do
Begin
New (pactual);
If ptemp^.num > pauxilary then
Begin
Pactual^.num := Pauxilary;
Pauxilary:= pauxilary^.next;
End;
If t = nil then
Begin
T := pactual;
M := pactual;
End
Else
Begin
M^.next := pactual;
M := pactual;
End;
End;
End;

Now Linear data Structures

Binary trees
It is a finite set of elements that is either empty or in portioned into tree disjoint subsets.
- The first subset contains a single element called the root of the tree.
- The other two subset are themselves binary trees called the left and right sub trees of the original tree.
Note A left or right subtree can be empty each of the binary tree is rolled a node of the binary tree.
Climbing the
ROOT Descending
tree A
the tree

B C
F

D I
E
Right
H subtree
Left subtree

The absence of a branch indicates an empty sbtree e.g. Left subtree rooted at node C
- Binary tree rooted at d, e, h, and I have empty right and left sub trees.
- A is the further of B and B is left son of A.
- A node that has no son is called a leaf.
- Two nodes are brothers if they are left and right sons of the same father e.g. B & C.

STRICTLY BINARY TREE


- It is a binary in which every non- leaf node has non-empty left and right sub trees.
- A strictly binary tree with N leaves always contains ( 2n 1) nodes.

LEVEL OF NODES
- It depends on the length of the branches from the root.
- The root has level zero and the level of any other node is one more than ints level of its father.

DEPTH OF A BINARY TREE


- It is the maximum level of any leaf in the tree.
- If a binary tree contains m nodes at level L then it contains at most 2m nodes at level L + 1 and it can contain at most 2 L nodes
at level L.
- A binary tree of depth d contains exactly 2d nodes at level d
- The total number of nodes in a complete binary tree of depth d is equal to the sum of the number of nodes at each level.
i.e. the total number of nodes
tn = 20 + 21 + 22 . 2d = d 2 I
I=0
2 d+1 - 1
1) Prove for d = 0
2 0 = 2 0+1 - 1
1=1
2) Prove for d = 1
2 0 + 2 1 = 2 1 +1 1
3=3
3) We assume it is true for d = k
2 0 + 2 1 + 2 2 + 2 k = 2 k + 1 1
4) We prove for d = k +1
2 0 + 2 1 + 2 2 + 2 k + 1 = 2 k + 2 1
2 k + 1 - 1 + ( k + 1 ) k term = 2 k + 2 1
2 k+1 - 1 + 2 k+1 = 2 k+1 + 2 k+1 - 1
= 2 k + (1 + 1) 1
= 2 k+1+1 1
= 2 k+2 1
Since it is for d = 0, d = 1 it is also true for any integer k > 0

USEFUL OPERATIONS IM THE CONSTRUCTION OF BINARY TREES


1. Make tree (x) it creates a new binary tree constitution of a single node with information filed x and returns a pointer to that
node.
2. Setleft (p, x) Accepts p to a binary tree node with no left sons. It creates a new son of node p with information x.
3. Setright (p, x) Accepts a pointer p to a binary tree node with no right son. It creates a new right son of node p with
information x.

TRAVERSING A BINARY TREE

- This refers to passing through the tree and enumerating each of its node once.
- We may simply want to print the contents of each node as we enumerate it or process it in some other way. In either case we
speak of using each node as it is enumerated.
- There are 3 methods of traversing trees these are
a) Preorder (Depth first order).
b) Inorder (symmetric order )
c) Post order

NB The only difference among these methods is the order in which these 3 operations are performed.

ALGORITHIMS
1. Preorder ( RT, L, R).
a) Visit the root.
b) Traverse the left subtree
c) Traverse the right subtree.

E.g.

. A

B C

D F F G
A B C D E F G

2. Inorder ( L, RE, R)
a) Traverse left subtree.
b) Visit the root node.
c) Traverse the right subtree.

E.g. For fig 1


D, B, E, A, F, C, G
3. Past order (L, R, RE)
a) Traverse left subtree.
b) Traverse right subtree.
c) Visit the root node.

D, E, B, F, G, C, A

Question
Obtain the in order, preorder, post order transversals of the following binary trees.

a)
A

B E
G
D
C F

P
R
H
b) A

C
B

E F
D

C)
*

* -
12 18 36 48 16
/
Preorder Inorder Pastorder
A ABDCEFHGPR DBCAFHEPGR DCBHFPRGEA
B ABDCEFG BDAEGFC DBEGCA
C * + 12 18 36 + 48 16 12 + 18 * 36 48 / 16 12 18 + 36 48 16 1 -

Q2 Represent the expression


(a + (b c) * ( c d- e) / (f + g + h)
Using binary tree.

1
. +

- -
a 1

d e
b
b c
+

f
g
Question 3. Represent the expression ((A + B ) C * ( D + E ) ) * ( F / G) Using binary.
*
- *
X

+ /
C
+ F G
A B

D E
*

/
-
F G
+ K

+
A C
B

E
D

Question 4. Construct a tree that gives the following:

Inorder : E I C F J B G D K H Z A
Preorder: A B C E I F J D G H K L

1 2 3 4 5 6 7 8 9 10 11 12
E I C FJ B G DK H ZA

ABCE IFJDGHKL
12 6 3 1 2 4 5 8 7 10 9 11

B
D
C

G H
E
F
L
= K
J
-
- It is a sorting method that involves the construction of a binary tree.
- In the construction of the binary tree we seen the elements to be sorted from left to right.
- The first element becomes the root any other element less than the root becomes the left subtree.
- Elements equal to greater than the root element becomes the right subtree.
- We then seam the tree inoreder e.g. sort the following element.

Binary tree sort


60 50 70 30 55 65 70 62 68

< >
60

50
70

30
55 70
65

62 60

30 55 60 62 65 68 70 70

If we want to sort the elements in descending order the binary tree constructed a follows.
- All elements greater or equal to root element become the left subtree and all elements less than the root becomes the right sub
trees.
- We then harvest the tree in order.

INORDER : D B E A F C G
POSTORDER: D E B F G C A

1 2 34 5 67
DBEAFCG
D EB F G CA
1 3 2 57 6 4

Application of stacks
- Stacks are applied in the Rollorso Polish Notation (RPN)
- The task of a compiler is to generate machine language instructions required to carry out the source program written in a high
level language.
- The other task is to generate the machine instruction for evaluating arithmetic instructions e.g. x:= A* B + C
- The required compiler must generate machine instructions to
a) Retrieve the value of A from the memory location and load it into the accumulative register.
b) Retrieve the value of B and multiply it by the value in the Acc register.
c) Retrieve the value of C and add it into the Acc register.
d) Store the value in the accumulative register in variable x.

Most expressions are written using infix notation in which the operator is placed between operands.
- For the computer to evaluate the expression they should be condoned to post for x notation in which the operator follows the
operands also knows as the reverse polish notation.
- Algorithm to convert information to postfix.
- Initialize an empty set.
- Repeat the following until end of expressions reached.
a) Get the next input broken (the token can be constant, variable, operand, arithmetic operation, left parenthesis,
right parenthesis)
b) If token is
1) A left parenthesis push it onto the stack.
2) An operator if the stack is empty or token as high priority that the top of element push when onto the stack
otherwise pop an operator from the stack and display it. Then repeat the operation of the token with the next
stack item. NB a left parenthesis in the stack is assumed to have a lower priority than any others.
3) Operand display it.
4) Right parenthesis
- For the right parenthesis pop and display stack elements write left parenthesis is an pop it also but do not display it.
- When end of infix is reached pop and display items until the stack empty.

Procedure Quicksort (var data : arraytype, first, last : integer)


Var
Splitpoint : integer;
Begin
If first < last
Then
Begin
Split ( data, first, last, splitpoint);
Quicksort (data, first, splitpoint 1);
Quicksort ( data, splitpoint + 1 , last);
End;
End;

Procedure split ( var data: arraytype; first, last :integer, var splitpoint :integer);
Var
Right, left : integer;
V : integer;
Begin
V := data [first];
Right := first + 1;
Left := last;
Repeat
(* move to the right until element ><.*)
while ( right < left ) and ( data [right] < = v)
do
right := right + 1;
(* check end condition.*)
if (right = left ) and (data[right] < = v)
then
right := right + 1;
(* Move left to the left until elements < = V*)
while (right < = left) and (data [right] > v) do
left := left -1;

if right < left


then
begin
swap (data[right], data[left]);
right := right + 1;
left := left -1
end;
until right > left;
(* swap first element with splitpoint element)
swap ( data[first] , data[left]);
splitpoint := left
end;

1. Repeat the following until the end of either list


- If first item in list1 > first item in list 2
- First item in list :=first item list
- Move to the next element of list1
otherwise
- If first
First item in list3 := first item in list 2
Move to the next element in list 2
2. If the end of list1 is reached copy the remaining elements to list3.
Else
Copy the remaining elements from list2

P
Inorder : B F G H P R S T W Y Z
Preorder: P F B H G S R Y T W Z
Postorder: B G H F R W T Z Y S P S
F
Procedure takeln( ls:linkedlist; l , u :integer);
Begin
Ptemp := pfirst; Y
R
B
While ptemp < > nil do
Begin H
If (ptemp6.n ><) and (ptemp6.n <Tu) Z
Then
Begin
G
Ptemp := ptemp6.next;
End
W
Else
Ptemp := ptemp^.next;
End;
End;

Procedure Merge (ls, li : linkedlist)


Var
Ptemp, pfirst : point;
Begin

QUEUES IMPLEMENTED STATICALLY


Assuming the following declarations
Type
Queue = record
Front, rear : integer;
Item : Array [1.. max] of infortype;
End;
Var
Q: queue;
Procedure push (x : infotype, var q: queue)
Begin
If q.rear > = max then
overflow exit
else
begin
q.rear := q.rear;
q.item [ q.rear] := x;
if q.front = 0 then
front := 1;
end
end;

Procedure pop (x:infortype, var q:queue)


Var
I: integer;
Begin
A := item [q.front];
q.front := q.front +1;
for I := 1 to q.rear do
begin
q.item[I] := q.item[I + 1]
q.rear := q.rear 1;
end;
end;

b) For I := 1 to n do
Begin
If s[I] < 0 then
Begin
Rear := rear + 1;
Q[rear] := s[1];
End;
End;

c) For I := 1 to rear do
begin
for j := I + 1 to rear do
begin
if q[j] > q[I] then
writeln q[I]
else
begin
temp := q[I];
q[I] := q [j];
q [j] := temp;
end;
end;
end;

Pointer a data type that is only used in the heap.


- Variable of this type return address of data in the heap.
Nil pointer It is pointer that points to no specific pointer or address. It makes the end of the linked lists.

Procedure reverse (var start : pointer);


Var
Currtent,prev, next :pointer;
Begin
Current := start;
Priv := nil;
While current < > nil do
begin
Next := current^.link;
Current^.link := prev;
Prev := current;
End;
Start := prev;
End;

Procedure search; (sets)


Var
X: integer;
Begin
Readln (x);
If x in s then
Writeln (found);
Else
Writeln (not found);
End;

Procedure Insert(var first, pointer;name: string);


Var
Ptemp, pactual,pauxilary: pointer;
Begin
New (pactual);
Pactual^.name := x;
Pactual^.next := nil;
If pfirst^.name < x then
Begin
Pactual^.next := pfirst;
Pfirst := pactual;
End
Else
Begin
Ptemp := pfirst;
While ptemp^.name < x do begin
Pauxilary:= ptemp;
Ptemp:=ptemp^.next
End;
Pactual^.next := ptemp;
Pauxilary^.next := pactual;
End;
End;
Sample exam questions

Question 1
Define the following terms as they are used in data structures and algorithms.

(i) Pseudocode
(ii) Algorithm
(iii) ADT
(iv) Data abstraction
(v) Pointer [ 10 marks]

Question 2
Distinguish between the following, supporting your answers with skeleton program segments

(a) formal parameters and Actual parameters


(b) Procedures and functions
(c) Repeat.. Until and While Do
(d) IF and CASE structures
(e) Pass by value and Pass by reference [ 20 marks]

Question 3
Given two 2 x 2 matrices, A and B, Write a program ( using procedures and functions) that accepts the two matrices and find their product as matrix C.
[ 30 marks]

Question 4
(a) Write an algorithm that performs a sequential search on an array of items.
(b) Write a procedure that counts the number of nodes in a linked list and print the number of nodes
[20 marks]
Question 5
Assuming the following declarations
Const
N =99;
Type
Numset = set of 1..n;
Var
S : Numset;

(a) Write a procedure to build a set S of size determined by the user [ 10 marks]
(b) Search for an integer determined by the user in the set [ 10 marks]

Question 1

Define the following terms as they are used in data structures and algorithms.

(vi) Pseudocode
(vii) Algorithm
(viii) ADT
(ix) Data abstraction
(x) pointer

Question 1
(i) Define stack data structure
(ii) Describe the features/ characteristics of a stack data structure ( also look at the diagrammatic interpretation of stacks)

Question 1
(c) Write an algorithm that performs a sequential search on an array of items.
(d) Write a procedure that counts the number of nodes in a linked list and print the number of nodes

Question 1

Given the following declaration:-

Type
Student = Record
Stud_num : integer;
Stud_name: String;
Class : String;
End;

Write procedures to perform the following:-


a) Create a file of students
b) Delete records
c) Edit records

Question 1
(i) Define recursion
(ii) Write a recursive function (fact) to calculate the factorial of a number 9n0 passed as a value parameter.

Question 1
(i) Obtain the preoder, inorder and postorder traversal of a give tree
(ii) Define graph data structure
(iii) Find the degree and indegree of a graph
(iv) Distinguish between connected and complete graph

Question 1
Write an algorithm to build a single linked list

Vous aimerez peut-être aussi