InfoStruc

Preview:

Citation preview

Csc326 – Information Structures

Dr. Carl J. De Pasquale carl.depasquale@csi.cuny.edu Blackboard C++ classes and data structures –

Childs – ISBN 978-0-13-158051-0 Office Hours by appointment

CSC 326 – Information Structures Introduction – CSC226 Coding, Coding Style,

Abstract Data Types and other C++ features

Recursion Searching Linked Lists Templates Stacks Midterm Queues and Trees Sorting Final

Lab 1 – Style and Format Lab 2 – Try/Catch/Throw Lab 3 – Recursion Trace Lab 4 - Linear Search Lab 5 – Binary Search Lab 6 – Associate Array Lab 7 - Dynamic Associate

Array using Linked Lists Lab 8 – Infix/Postfix using

Stacks Lab 9 – Binary Sort Tree

Syllabus

Grading5 – 6 Labs 30%(Labs must be turned in on the Due

date or they will not be accepted and no credit will be received for work)

Mid-Term – 25% Final – 35% Class Participation – 10%

Syllabus

Reading Chapters 1-6 Chapter 13 Recursion Chapter 09 Time Complexity Chapter 11 Hashing – Searching Chapter 10 Link List Chapter 8 Stacks

Syllabus

GradingAccumulated Points Letter Grade

100 – 95 A

94 – 90 A-

89 – 87 B+

86 – 83 B

82 – 80 B-

79 – 77 C+

76 – 73 C

72 –70 C-

69 – 55 D

<55 F

Overview

Programming Issues Modularity Style Modifiability Ease of use Fail safe programming Debugging Testing

Overview

Programming Style Private data Call by reference not by value Method usage associated with data Non global data Error handling Readability Documentation

Review Style Document

Overview

Abstract Data type

Coding Style, Comments, Variable Naming Convention

UML Algorithm

Efficiency

Literate Programming Code for the Reader Be Clear and Concise

Think before you Write! Always Follow the

Guidelines Ask yourself, can I justify

a deviation

Overview

Structure Abstract

Data Types (ADT)

In C++; or in general any Object Oriented (OO) Programming Language uses a class to represent the ADT

Class - Organizational Structure

Stores structure Stores Data access and

data manipulation functionality in a common container

Overview

C++ Review and Examples

Overview Abstract Data Types Pointers & Storage Classes,

Constants/#defines Overload

Functions/Operators References Pointer arithmetic

Contents of Address of

Try/Catch/Throw Template

Overview

Abstract Data Typestruct name { variables of different type stored in a reference group}

struct stbankRecord {char* cpaccount;

/* dynamic string */short saccountType;

/*0-checking, 1 savings, 2 money market */float finterestRate ; /* in percent */

};

Overviewstruct stbankRecord {

char* cpaccount; /* dynamic string */

short saccountType; /*0-checking, 1 savings, 2 money market */

float finterestRate ; /* in percent */}; /* storage not allocated */

struct stbankRecord stbr; /*stbg allocated storage*

Overview

Abstract Data Typeclass name { private: //variables

char* cpaccount; /* dynamic string */short saccountType; /*0-checking, 1 savings, 2 money market */float finterestRate ; /* in percent */

public:name() {} /* constructor */

};

Overview

Elementary and ADT Storage Classes Automatic Static Dynamic

Overview#define CPACCTSIZE 32 /*C preprocessor */const int cpacctsize = 32; /* C++ */

static int iarrayLength = 5;auto int iarrayLength = 5 ;

Dynamicstbr.cpaccount = malloc (CPACCTSIZE); /*C*/stbr.cpaccount = new char[cpacctsize]; /*C++*/

Always verify storage allocation is successfulif ( stbr.cpaccount == (char*)Null ) /* allocation

failed */

Overview Pointers Address

Contains an address to an ADT Defined in C and C++ as

* pointer, & address int* pigoldenRatio; //pointer to

integer int pigoldenRatio; //integer &pigoldenRatio ; //address of

Overview

try catch throw initialization

Overviewclass Hello : public std::exception {private:

char cshelloReply [ imaxStringLength ];

public:class ClassName {

private: int ivar1;

int ivar2; public: ClassName(int i) : ivar2(ivar1), ivar1(i) { };

ClassName (int i) { ivar2 = i; ivar1 = ivar2; }

int mgetter () { return ( ivar1) ; }};

}

Overview

if ( exception ) throw ClassName (integer variable); //custom

if ( exception ) // standard exception{ char cstmp [64] ; sprintf(cstmp, "%s %d",“error message", ierrorCode) ); throw out_of_range (cstmp);}

Overview

try{ h.setcshelloReply

("Mordor - One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them\n");}catch (cHello::Length l ) { cerr << " String overflow - " << l.mgetLength() << " needed" << std::endl;}

Overview

catch (std::out_of_range r) catch (std::invalid_argument ia) catch (std::bad_alloc alloc) catch (std::bad_cast cast) catch (std::bad_exception be) catch (std::overflow_error ofe) catch(...)

Overview class divideException : public std::exception{ public: divideException::divideException() : std::exception

("attempted to divide by Zero") {} };

double divide ( int numerator, int denominator) { if ( denominator == 0) throw divideException(); if ( denominator < 0) throw long(denominator);

return static_cast<double>(numerator)/denominator; }

Overview try { double result = divide(6,-1); cout << result << " " << std::endl; } catch (divideException &DE){ cout << "Divide Exception Occurred: " << DE.what() <<

std::endl; } catch (long l){ cout << "long Exception Occurred: " << l <<

std::endl; }

Overview Function Parameters

Pass by value Pass by reference

void value (int* arg1) { //reference*arg1 = *arg1 +27 ;return ;

}

void value ( int arg1 ) { //valuearg1++;return ;

}

cout << iparameterPassed << std::endl ;

value(iparameterPassed);cout << iparameterPassed << std::endl ;

value(&iparameterPassed);cout << iparameterPassed << std::endl ;

Overview Const

char* cc = "56"; const char* const aa = cc; char*& bb = (char*&)aa; bb = "violates const"; cout << &aa << " " << &bb << " " << &cc <<

std::endl; cout << aa << " " << bb << " " << cc <<

std::endl;

OverviewClass cassociateArray {

struct tassociateArray {char* csindex ;int ivalue ;} tas [ 128 ] ;

int& operator[] (const char* index) {for (int i = 0 ; i < inumOfEntries ; i++ )

{ if ( tas[i].csindex != (char*)NULL && strcmp ( tas[i].csindex, index ) == 0 ) { //dup return tas[i].ivalue ; }

}

}cassociateArray mot = cassociateArray();mot["const"] = 0 ;

Overview#include <iostream>#include <string>#include <io.h>#include <memory.h>#define IMEMORYALLOCATION 32using namespace std;

intmain(){

char *cpallocMemory ;const int imemoryAllocation = 32;imemoryAllocation = 54; //compile error

if ( (cpallocMemory = (char*)malloc(IMEMORYALLOCATION)) != (char*)NULL) printf("Memory Allocation successful\n");

if ( (cpallocMemory = new char[imemoryAllocation]) != (char*)NULL) cout << "Memory Allocation successful" << std::endl ;

return 0;}

Overview#include <iostream>#include <string>#include <io.h>#include <memory.h>

using namespace std;

int max (int a, int b){return a>b ?a : b;

}int max ( int a, int b, int c) {

if ( a > b ) if ( a > c ) return a; else return c;else

if (b>c) return b; else return c ;

}

Int main(){cout << max (5, 10) << std::endl ; //max is overloadedcout << max (18, 27, 35) << std::endl ; //max is overloadedreturn 0;

}

Overview

// can’t change either variable const int iintVariable = 101; const int& irefIntVariable = iintVariable;

cout << iintVariable << " " << irefIntVariable << std::endl; //variable and variable reference

____________________________________________________________________

// can’t change reference but can change the anchor variable value int iintVariable; const int& irefIntVariable = iintVariable;

iintVariable = 97;cout << iintVariable << " "

<< irefIntVariable << std::endl; //variable and variable reference

Overview#include <iostream>#include <string>#include <io.h>#include <memory.h>

#define IMEMORYALLOCATION 32

using namespace std;

int max (int a, int b){return a>b ?a : b;

}int max ( int a, int b, int c) {

if ( a > b )if ( a > c ) return a;else return c;

else if (b>c) return b;else return c ;

}

intmain(){ int iunsortedArray [10] = {19,5,20,4,8,15,12,13,1,2};const int iintVariable = 95;const int& irefIntVariable = iintVariable;char *cpallocMemory ;const int imemoryAllocation = 32;//imemoryAllocation = 54; //compile error

if ( (cpallocMemory = (char*)malloc(IMEMORYALLOCATION)) != (char*)NULL) printf("Memory Allocation successful\n");

if ( (cpallocMemory = new char[imemoryAllocation]) != (char*)NULL) cout << "Memory Allocation successful" << std::endl ;

cout << max (5, 10) << std::endl ; //max is overloadedcout << max (18, 27, 35) << std::endl ; //max is overloaded//iintVariable = 97;cout << iintVariable << " " << irefIntVariable << std::endl;

//variable and variable reference

cout << iunsortedArray[5] << " " << *(iunsortedArray+5) << " " << *iunsortedArray+5 << std::endl ;

cout << iunsortedArray[5] << " " << &iunsortedArray[5] << " " << &iunsortedArray[5] +5 << " " << *iunsortedArray+5 << std::endl ;return 0;

}

Overview

Overview#include <iostream>#include <fstream>#include <iomanip>

using namespace std;

template <class T>inline T& max(T&a, T&b) {

return a > b ? a : b;}

intmain(int argc, char** argv){

cout << max (1,2) << std::endl ;

cout << max (1.234,0.0433) << std::endl ;

cout << max ('a', 'b') << std::endl ;

return 0;

}

Overview#include <iostream>#include <fstream>#include <iomanip>

using namespace std;

template <class T1, class T2>T1* Min (T1* a, T1* b, T2 ilen) {

int min = memcmp ( (char*)&a[0], (char*)&b[0], ilen )

if (min == -1 ) return &a[0];elseif (min == 1 ) return &b[0];else return &b[0];

}

int main (){int a = 5;int b = 18;

double c = 3.234;double d = 1.123 ;

char e = 'b' ;char f = 'z' ;

char sa[] = "Giraffe";char sb[] = "Zebra ";

cout << *Min ( &a, &b, sizeof(int) ) << std::endl;

cout << *Min (&c, &d, sizeof(double)) << std::endl ;

cout << *Min (&e, &f, sizeof(char)) << std::endl ;

cout << Min ( &sa[0], &sb[0], strlen(sa) ) << std::endl;

return 0;}

Overview

Unified Modeling Language (UML) Class diagrams – depict static

structure of the system

Class Name

Attributes, variablesOperations, methods

Overview Unified Modeling Language (UML) Class Diagram

1

0..*

B

D C

E F

B Contains D C Contains D E and F are

inherited from D 1, 0..* -

Multiplicities

Overview Unified Modeling Language (UML) Sequence Diagram describes how objects (Classes)

interact with one another Class A invokes Class

B, Class B returns data to Class A

Class A processes returned data, invokes class C

Class C processes data, invokes local method, returns data to class A

A B

C

Method

Info Ret

Method

Info Ret

Local Method

Overview

Unified Modeling Language (UML) UML

Recursion Recursion Procedure that invokes itself

Each Invocation stores the state of the call

Parameters of the invocation

Local variables Return value Registers Calling address Return address

Recursion Recursion Code

Fibonacci Golden Ratio

(1.61803399)

Golden Ratio

Fibonacci Number Sequence Fibonacci(0) = 0 Fibonacci(1) = 1 Fibonacci (n) = fibonacci(n-1) + finonacci(n-2)

#include <iostream.h>#include <stdlib.h>void main(){

int num;int fibo(int);cout << "Enter a number: ";cin >> num;if ( num < 0 ) { cout << “Invalid Numeric Value “ << endl; exit(0);}cout << "The answer is " << fibo(num) << endl;

}int fibo (int n){

if (n==0 || n ==1) return n;else return (fibo(n-1)+fibo(n-2));

}

2

51

Recursion

0 1 1 2 3 5 8 (6th term) Fibo(5) + Fibo(next Slide(4))

Fibo(4) + Fibo(3) | |Fibo(3) + Fibo(2) Fibo(2) + Fibo(1) | | |Fibo(2)+Fibo(1) Fibo(1) + Fibo(0) Fibo(1) +

Fibo(0) |Fibo(1) + Fibo(0)

Recursion

0 1 1 2 3 5 8 (6th term)

Fibo(4) | Fibo(3) + Fibo(2) | | Fibo(2)+Fibo(1) Fibo(1) + Fibo(0) |Fibo(1) + Fibo(0)

Recursion Recursion Code

Factorial

#include <iostream.h>#include <stdlib.h>void main(){

float num;float fact(float);cout << "Enter a number";cin >> num;if ( num < 0 ) exit(0);cout << "The answer is " << fact(num) << endl;

}

float fact(float num){

float ans;if (num == 0)

return 1;else{

ans = num*fact(num-1); cout << num << "!= " << ans << endl;

return ans;}

}

Recursion 5 Factorial (120) Ans = 5 * Fact(4) 4 * Fact(3) 3 * Fact(2) 2 * Fact(1) 1 * Fact(0)

Recursion

Towers (n, A, B, C) { if ( n ==1 ) print “move”, A “ to ”, B else { Towers ( n-1, A, C, B) //source, aux, dest print “move”, A “ to ”, B Towers (n-1, C, B, A) //aux, dest, source }}

Recursion

RecursionStep Call From N Print

7 Print, Pop 1 A B C A to B

Print, Pop C to B

Print, Pop C to A

6 1 C A B

5 First call 2 C B A

A to B

B to C

4 Second call – S2

1 B C A

Print, Pop A to C

Print, Pop A to B

3 1 1 A B C

2 1 2 A C B

1 initial 3 A B C

Time Complexity

Efficiency

Order Time Estimate

Logarithmic

O(log2 n) Microseconds

Linear O(n) 0.1 seconds

Linear Logarithmic

O(n(log2 n)) 1-2 seconds

Quadratic O(n2) Minutes

Polynomial O(nk) Hours

Exponential

O(kn) Intractable

Factorial O(n!) Intractable

Time Complexity

Examples Algorithm

Order Time Estimate

Binary Search

O(log2 n) Microseconds

Linear Search

O(n) 0.1 seconds

Heap, Quick Sort

O(n(log2 n)) 1-2 seconds

Selection, Bubble Sort

O(n2) Minutes

Time Complexity Array contains 1000 elements

Binary Search O(log2 n) 1000/2, 500/2, 250/2, 125/2 63/2, 32/2, 16/2, 8/2, 4/2 2/2 Ten (10) compares to find number log2 1000 = 9.965784002, 2^ 9.965784002 =

999.9998041 loge 1000 = 6.907755279 * 1.442695 = 9.965784002

Time Complexity

Graphical Representation

n

O(n)

n3

n2

nlogn

logn

n

C++ Functions

Reading and writing files #include <iostream> #include <fstream> #include <iomanip> Define file location and mode

fstream filehandle (file location, file mode); fstream finumbers(“C:\\filenumbers.txt”, ios::in)

Read in an input line Char* cpinputLine = new char[128]; finumbers.getline(cpinputLine, 128); formatted input line 50:45:45:6767:34:34:……

C++ Functions

Populate array #include <iostream> #include <fstream> #include <iomanip> Read in an input line

Char* cpinputLine = new char[128]; finumbers.getline(cpinputLine, 128); formatted input line 50:45:45:6767:34:34:……

Strtok Char csConvertNumber [ 16 ]; csConvertNumber = strtok (cpinputLine,”:”); for ( int i = 0 ; i < 50 ; i++) {

inumberList[i] = atoi (csConvertNumber); csConvertNumber = strtok (NULL,”:”);

}

C++ Functions

Simple cout formatting Setw(‘character ‘); //set width Setfill (‘character ‘ ); // set fill character Cout << setw(5) << setfill (‘0’)

<<inumber; Prints a number 5 characters long prefaced by

zeroes, as necessary

Searching

Searching Sequential – Unordered List

Start from the beginning look at each element until a match is found of the list is exhausted

Binary – Ordered List Split list in half - look for

element in top half of list or bottom half of list depending on the midpoint value

Searching

Hashing Organizational Structure All information is

physically represented and stored as a flat model

Can logically appear to be stored in multiple dimensions

A tree A queue A stack

Implemented as a linked List or an array or both

Searching Real world

hashing and searching

Unix Operating System File/Buffer Management Memory Management

Java Virtual Machine Profiler Interface Agent

Class/Method Management

Searching

Searching Sequential Binary Hashing Methods

Direct Subtraction Modulo Division Digit Extraction Mid square Folding Rotation Pseudo Random

Generation

Searching

Searching Hashing Methods Direct – Key is the address

into a list Key(115) = 115

Subtraction – N is subtracted from the key and the key is used Direct

Key(115) – 100 = 15 Modulo Division – Key % n

is the address into a list Key(115) % 10 = 5

Searching

Searching Hashing Methods Digit Extraction – Use fixed

set of digits extracted from the key

Key(2783) = 28 Key(3497) = 39

Midsquare – Square key use middle digits as key

Key(2783 ) = 7745089 = 450

Searching

Searching Hashing Methods Fold Shift – key is split in

two segments; rotated, added and truncated

Key(2783) = 27 + 83 = 110, drop left most digit = 10

Fold Shift – key is split in two segments; rotated, added and truncated

Key(2783) = 72 + 83 = 155, drop left most digit = 55

Searching

Searching Hashing Methods Rotation – Key right most

digit is shifted to the left Key (2783) = 3278

Pseudo Random Generation – linear equation used to derive key

Key = ax + c A = 12 X = 2783 C = 6 Key = 33402

Apply other hashing methods to key

Searching

Searching – read cache of a file system Need to efficiently store and access cached

data blocks Files are comprised of many data blocks An operating system stores disk blocks as 1024

byte data blocks Block 0 uses bytes 0-1023 Block 1 uses bytes 1024 – 2047

The address for block 0 is 0 * 1024 The address for block 1 is 1 * 1024

Searching

Searching Caching read data blocks

Data blocks anchored off of a fixed size memory array of pointers (char*)

char* datablocks [ 524288 ] ; 1,099,511,627,776 – 1 terabyte file

system Has 1,073,741,824 data blocks

Fast access needed to determine if block is in memory

Searching

Searching Read in data block 5,467,863 5,467,863 % 524,288

Hash 224,983 if (datablocks [224983 ] == (char*)NULL) {} //block not in

core else {} // block may be in core

Possible 2048 duplicate hashes per hash block

5,992,151 % 524,288 Hash 224,983

Searching Collision Resolution

Open – When a collision occurs the prime area (buckets) are searched to find a free/unoccupied slot

Linear Probe (Doubling) Add 1 to the current address until a free/unoccupied slot is found

Quadratic Probe (Doubling) Add a value other that 1. 22 for the second collision, 32 for the third collision, etc

Searching Collision Resolution

Open – When a collision occurs the prime area (buckets) are searched to find a free/unoccupied slot

Pseudo Random Collision Resolution linear equation used to derive newKey

newKey = ax + c Key offset – (Double Hash)

(Key(n)/list size + old collision address ) % list size

Linked List

Searching Collision Resolution

Open – When a collision occurs the prime area (buckets) are searched to find a free/unoccupied slot

Linked List Resolution

Searching Hashing, Searching and Recursion

Genetic

InitPopulation Sort

ElementAtsetElementAt

Stack Trace - Link List

Method - Hash List

Searching class ctNode { private: string sfileWord ; // used to allocate and store input

word int iwordCnt ; // number of word occurrances ctNode* ctpforward ;

// pointer of type ctNode, points to next link list element };

class ctNode { private: string sfileWord ; // used to allocate and store input

word int iwordCnt ; // number of word occurrances ctNode* ctpforward ; ctNode* ctpback ; };

Searching Dijkstra searching algorithm

Reaches final state at each iteration of algorithm A graph is a collection of nodes and directed arcs or

edges

Searching Dijkstra searching algorithm requirements

Weighted directed graph Identify a starting node and a destination node

Algorithm purpose Find the shortest path not back tracking

No back tracking or a greedy algorithm

Searching

http://www.dgp.toronto.edu/people/JamesStewart/270/9798s/Laffra/

DijkstraApplet.html

HNL

2932SFO

2555LAX

4298ORD

DWF

LGA

MIA

5147PRD

2555

849

802

1843

174337

7

1233

1205

1120

142

1387

Searching

Algorithm Initialization - assign weights to all edges Visit the starting node (or node) and

identify all adjacent nodes Determine least distance (weight) to each

node, Label the node with the distance (weight) Repeat Stop when all nodes have been visited

Searching

Algorithm Initialize “nodes” matrix to zeroes Initialize “PointerToByNode” array to -1 Initial “distance” array to 2^31 (very large number) Read in number of node/edge pairs Read in from-to-weight using node number as index to(row) from(col) Loop k,1 to “numberOfNodes”

Loop i,1 to “numberofNodes” If (nodes[k][i])

If (nodes[k][i] +distance[k] < distance[i]){ distance[i] = nodes[k][i] +distance[k]; pointedToByNode[i] = k; }

Genetic Searching Genetic Searching

Algorithm

Create InitialPopulation

TerminationCriteria Met

OutputResults

Stop RunYes

EvaluateFitness ofPopulation

Select GeneticOperatorBased onProbability

Select TwoIndividualsBased onFitness

Select OneIndividualBased onFitness

PerformCrossover

Insert Offspringinto Population

PerformMutation

Insert Mutantinto Population

Crossover Mutation

Genetic Searching

Genetic Searching Algorithm

• The genetic algorithms can be thought of as a highly efficient search technique that transforms individual members of a target population into a fitter next generation

• In this context, each member of the population is stored as a unique bit string and a fitter generation denotes a better approximation of a solution

• To manipulate the population, genetic algorithms rely on three primary operators, fitness, crossover, and mutation. Goldberg (1989) and Koza (1994) explain that the fitness operator is patterned after Darwinian survival of the fittest and is used to identify members of the population that will be allowed to reproduce

Genetic Searching

Genetic Searching Algorithm

The crossover operator, modeled after human reproduction, randomly selects two of the fittest members of the population to mate. During mating the crossover operator randomly selects and swaps portions of the selected bit patterns. Paralleling human evolution, the mutation operator has an extremely low probability of occurrence. Mutation causes a randomly chosen bit of a randomly selected member of the population to be flipped

Genetic Searching

Genetic Searching Algorithm

The initial population is created The algorithm repeats until the

termination criterion or criteria are met

The termination criterion could be a maximum generation limit or threshold on the fitness of an individual

As the algorithm executes, the population’s fitness is determined and the crossover or mutation operators are randomly executed

Linked Lists

Linked List - ADT

Contains one or more pointers

Contains application specific data

struct tlinkList {struct tlinkList*

tpright ;int ibinTreeVal ;

} ; // UniDirectionalstruct tlinkList {

struct tlinkList* tpleft ;

struct tlinkList* tpright ;

int ibinTreeVal ;} ; // BiDirectional

Linked Lists

Types of Linked Lists Ordered – Sorted Array or Binary Tree Unordered – Hash Collision List Fifo (queue) – Operating system

scheduler Lifo (stack) - Infix to postfix conversion

Linked Lists Linked List

Operations Search

UniDirectional BiDirectional

Linked Lists Linked List Operations

Insertion (Add) Uni/BiDirectional

Empty Head Tail Middle

Linked Lists Linked List

Operations Delete (Remove)

Uni/BiDirectional

Head Tail Middle

Linked Lists Search

do { if (list -> ibinTreeValue != Key ) {

// Found } list = list -> tpright ; }while ( list != (struct tlinkList*)NULL ) ;

Linked Lists Insert

while ( list -> ibinTreeValue != Key ) { if (list -> tpright == (struct tlistList*)NULL ) {

// End of list reached and value not in list, insert list -> tpright = new tlinkList ; Allocate Memory if (list != (struct tlistList*)NULL) { // If memory allocation succeeded, add element to list } else { Memory allocation Failed, throw allocation

error}

} list = list -> tpright ;}

Linked Lists string cminsertNode (string svalue) { ctNode* ctptmpHead = ctphead ; if ( ctphead == NULL ) { // allocate new and set head ctptmpHead = ctphead = new ctNode ; ctphead -> ctpnext = NULL ; ctphead -> sfileWord = svalue ; } else { //find last ctnode do { if ( ctptmpHead -> ctpnext != NULL ) ctptmpHead = ctptmpHead -> ctpnext ; } while ( ctptmpHead -> ctpnext != NULL ) ; // fall thru found last node ctptmpHead -> ctpnext = new ctNode ; ctptmpHead = ctptmpHead -> ctpnext ; ctptmpHead -> ctpnext = NULL ; ctptmpHead -> sfileWord = svalue ; } return ctptmpHead -> sfileWord ; }

class ctNode { friend class ctlinkList ; // friend class allowed to access private data private:

string sfileWord ; // used to allocate and store input word int iwordCnt ; // number of word occurrances ctNode* ctpnext ; // point of Type Node, points to next link list element };

Linked Lists Several string functions

string s1, s2, s3; s1 = “hello world”; s1[1] = “H”; s1.length() or s2.size(); s1.empty() ; // Boolean If ( s1 < s2) {} //relational s3 = s1 + s2 ; // concatenation s2.replace(1,6,”-”); s2.erase (1,6); s2.append (“ “);

Stacks

A stack is a First In Last Out (FILO) Queue

A stack can be implemented using an array

A stack can be implemented using a link list

Stacks Stack Operations

Push (Add an Element) Element is added to

the top of the stack

Stacks Stack Operations

Pop (Remove an Element) Element is removed

from the top of the stack

Stacks Non Primary Stack

Operations totalElements isEmpty lookAtTopElement

Queues and Trees

A queue provides a First In First Out (FIFO) operation

A queue like a stack can be implemented using an array

A queue like a stack can be implemented using a link list

Simple queue (FIFO) Advanced queue (FIFO with Priority)

Queues and Trees

Queues can be used to schedule work Every day queues (clients & servers)

Supermarket line Theater ticket line

Computer queues Operating systems

Process Middleware

Asynchronous processing Workload Distribution

Queues and Trees Trees are ADT that are implemented

using link lists The implementation representation

is similar to a bi directional link list Components of a tree

Root Depth Breadth In degree Out degree

Queues and Trees Pictorial Example

Root in degree (0) – out degree (2) Node in degree (1) – out degree (2) Depth (3) – Breadth (2)

Queues and Trees Pictorial Example

Branch Leaf (non zero out degree) Terminal leaf (zero out degree)

Queues and Trees Binary Sort Tree

5, 8, 9, 1, 3, 4, 2

5

1 8

9

42

3

Sorting Sorting Algorithms

Internal Insertion O(n2) Shell O(n1.25) Selection O(n2) Heap O(n log2 n) Bubble O(n2) Quick O(n log2 n)

External Balanced Natural

Sorting Sorting Algorithms

Insertion – Cards - data element in final position

15 - Wall - 18, 2, 9, 3, 30, 40, 51, 60, 7 Create two list within one list, each

separated by a wall Sorted list – Wall – Unsorted Choose first element of unsorted list

move it to correct location in sorted list 15, 18 – Wall - 2, 9, 3, 30, 40, 51, 60, 7 2, 5, 18 – Wall - 9, 3, 30, 40, 51, 60, 7

Sorting Sorting Algorithms

Shell sort - modified insertion 15, 18, 2, 9, 3, 30, 40, 51, 60, 7 n := 10 Inc1 := int(n/2) Inc2 := int(Inc1 /2) Inc3 := int(Inc2 /2)

Sort cells by each increment Once a switch is made reorder list

(backward) 2000 elements, 4,000,000 – 13,374

Sorting Sorting Algorithms

Selection – in each pass choose the smallest element of the unsorted list

Place it at the beginning of the unsorted list

Select and move the wall Wall – 15, 18, 2, 9, 3, 30, 40, 51, 60, 7 Wall – 2, 18, 15, 9, 3, 30, 40, 51, 60, 7 2 - Wall – 18, 15, 9, 3, 30, 40, 51, 60, 7 2 - Wall – 3, 18, 9, 15, 30, 40, 51, 60, 7 2, 3 - Wall - 18, 9, 15, 30, 40, 51, 60, 7

Sorting Sorting Algorithms

Heap – Tree Tree is complete or nearly complete Key at each node > descendents

Sorting Sorting Algorithms

Heapify (A, i) l =left(i) r = right(i) if ( l < heapSize(A) & A[l] > A[i]

then largest = l else largest = I

if ( r < heapSize(A) & A[r] > A[largest] then largest = r

if ( largest != i ) exchange A[i] with A[largest] Heapify (A, largest)

Sorting Sorting Algorithms

Bubble Compare element n with element n+1

Switch two elements Start from the first element

Stop when end of list reached and not switched elements

Sorting Sorting Algorithms

Quick Sort Select pivot element

Use median (n/2) or Order

left and middle left and right Middle and right Repeat until Left < middle < right

Sorting Sorting Algorithms

Quick Sort Erect two walls

15, 18, 2, 9, 3, 30, 40, 51, 60, 7 After Left and order right After Right and order left Pivot 3

3, 18, 2, 9, 7, 30, 40, 51, 60, 15 7, 18, 2, 9, 3, 30, 40, 51, 60, 15 7 – Wall - 18, 2, 9, 3, 30, 40, 51, 60, 15 - Wall 7 3, 2 – wall left wall right 9, 18, 30, 40, 51,

60, 15 2, 3, (pivot)7, 9, 18, 30, 40, 51, 60, 15 quick sort left(<pivot) – quick sort

right(>pivot)

Sorting Sorting Algorithms

Quick Sort Divide: Partition the array A[p..r] into

two subarrays A[p..q-1] and A[q+1..r] such that all elements in A[p..q-1] <= A[q] and A[q] <= A[q+1..r]

Conquer: Sort the two subarrays A[p..q-1] and A[q+1..r] by recursive calls to quick sort

Combine: Array are sorted in place therefore A[p..r] is sorted

Sorting Sorting Algorithms

Qsort ( A, p, r) If (p<r)

Then q = partition(A,p,r) Qsort (A, p, q-1) Qsort( A, q+1, r)

Sorting Sorting Algorithms

partition ( A, p, r) x = A[r] i = p – 1 for (j =p; j<r-1; j++)

if (A[j] <= x e = I + 1 exchange A[i] with A[j]

exchange A[i+1] with A[r] return I +1

Associate Array

Write an associate array class by modifying the sample code or writing from scratch

Convert the array used to story the associate array into a bi-directional link list

To test your associate array read the following text from a file and use the associate array to count the number of times each word in the following text occurs

“Egyptian tombs were usually divided into two areas, the closed and forbidden domain of the dead and the more accessible area where friends and relations of the deceased could make prayers and offerings. The boundary between these two areas was often marked by a stone imitation door, the so-called false door.”

Print each word and its occurrence could tassocArray tcwordCount = tassocArray; taa[word] = taa[word] + 1 ;

Hand in the source code, output and executable files

Associate Array Modify Lab 3 to include a hash bucket head and link list.

Define 26 hash buckets one for each letter of the alphabet. The ADT for a bucket head and link list.

To test the modified associate array read the following text from a file and use the associate array to count the number of times each word in the following text occurs

“Egyptian tombs were usually divided into two areas, the closed and forbidden domain of the dead and the more accessible area where friends and relations of the deceased could make prayers and offerings. The boundary between these two areas was often marked by a stone imitation door, the so-called false door.”

Print each word and its occurrence could tassocArray tcwordCount = tassocArray; taa[word] = taa[word] + 1

The link list is bi directional Hand in the source code, output and executable files Compare the iterations required to load each word using the

associate array Lab 3 and the modified associate Lab 4

Postfix Stack Algorithm Converting Infix to Postfix

We know that the infix expression (A+B)/(C-D) is equivalent to the postfix expression AB+CD-/. Let's convert the former to the latter.

* Variables (in this case letters) are copied to the output stack * Left parentheses are always pushed onto the stack * When a right parenthesis is encountered, the symbol at the top of the stack is popped off the stack and

copied to the output. Repeat until the symbol at the top of the stack is a left parenthesis. When that occurs, both parentheses

are discarded. * Otherwise, if the symbol being scanned has a higher precedence than the symbol at the top of the stack,

the symbol being scanned is pushed onto the stack and the scan pointer is advanced. * If the precedence of the symbol being scanned is lower than or equal to the precedence of the symbol at

the top of the stack, one element of the stack is popped to the output; the scan pointer is not advanced. Instead, the

symbol being scanned will be compared with the new top element on the stack. * When end of file on the input scan is reached, the stack is popped to the output until the stack is empty. Then the algorithm terminates. * If the top of the stack is a left parenthesis and the terminating symbol is scanned, or a right parenthesis is scanned when the terminating symbol is at the top of the stack, the parentheses of the original

expression were unbalanced and an unrecoverable error has occurred.

Evaluating postfix * The postfix expression to be evaluated is scanned from left to right bottom of stack to top of stack.

Variables or constants are pushed onto the stack. When an operator is encountered, the indicated action is performed using the top elements of the stack,

and the result replaces the operands on the stack

Postfix Stack Evaluation

Using the example stack class or you own, write the necessary code to convert the infix expressions to postfix and evaluate the postfix expressions (6+4)*9 6 4 + 9 * ((8/4)+8)*6 8 4 / 8 + 6 * 896*15/200 896 15 * 200 /

Binary Sort Tree Write a C++ program to create a binary

sort tree using the following numbers 18, 25, 32, 1, 15, 5, 10, 80

Create the sorted binary tree using procedural or recursive code

Walk the tree using a recursive algorithm. print the data in ascending and descending order

Walk Left, Print, Walk Right Walk Right, Print, Walk Left

Examples - .h #include <iostream> #include <fstream> #include <iomanip>

using namespace std;

const imaxStringLength = 64 ;

class Hello { private: char cshelloReply [ imaxStringLength ];

public: class Length : public std::exception{ private: int ilengthOverflow; public: Length (int i) : ilengthOverflow(i) { }; int getLength () { return ( ilengthOverflow ) ; } }; Hello() { strcpy (cshelloReply, "Hello "); } int setcshelloReply(char*); char* getcshelloReply() ; };

Examples - .Impl #include "Hello.h"

char * Hello::getcshelloReply () { return cshelloReply ; }

int Hello::setcshelloReply(char* csReply) { //if ( 6+strlen (csReply) > imaxStringLength ) throw Length(6+strlen

(csReply));

if ( 6+strlen (csReply) > imaxStringLength ) { char cstmp [64] ; sprintf(cstmp, "%s %d","String too Long, size ", 6+strlen

(csReply) ); throw out_of_range (cstmp); }

strcpy (cshelloReply+6, csReply); return 0; }

Examples - main #include "Hello.h"

int main() { Hello h = Hello() ; try { h.setcshelloReply (“Mordor - One Ring to rule them all, One Ring to find them, One

Ring to bring them all and in the darkness bind them\n"); } catch (Hello::Length l) { cerr << "Hello exceeded String Length " << l.getLength() << endl ; } catch (std::out_of_range l) { cerr << "Hello exceeded String Length " << l.what() << endl ; } catch (std::bad_alloc all) { } catch (std::bad_cast cast){ } catch (std::bad_exception){ } catch (std::overflow_error ofe){ } catch(...) { cerr << "Error not Caught..." << std::endl; } cout << h.getcshelloReply(); return 0; }

Examples Recursive Binary

Search – in Java

import java.lang.*;class Search {

int [] isearchArray ;int ilowerBound ;int iupperBound ;

int searcher ( int ll, int uu, int lk ) {

if ( ll > uu ) return -1;elseif ( lk < isearchArray [ (ll+uu)/2 ] )

return ( searcher ( ll, ((ll+uu)/2)-1, lk ) );elseif ( lk > isearchArray [ (ll+uu)/2 ] )

return ( searcher ( ((ll+uu)/2)+1, uu, lk ) ) ;else if ( lk == isearchArray [ (ll+uu)/2 ] ) { return (ll+uu)/2 ; }return -1 ;

} public static void main(String[] args) {

Search srch = new Search () ; }}

Examples Recursive Binary Search – in Java

Minor efficacies improvements

import java.lang.*;class Search {

int [] isearchArray ;int ilowerBound ;int iupperBound ;

int searcher ( int ll, int uu, int lk ) {

int isearchArrayIndex = (ll+uu)>>1;if ( ll > uu ) return -1;elseif ( lk < isearchArray [isearchArrayIndex ] )

return ( searcher ( ll, isearchArrayIndex -1, lk ) );elseif ( lk > isearchArray [isearchArrayIndex ] )

return ( searcher ( (isearchArrayIndex +1, uu, lk ) ) ;else if ( lk == isearchArray [isearchArrayIndex ])

{ return isearchArrarIndex ; }return -1 ;

} public static void main(String[] args) {

Search srch = new Search () ; }}