C++ and Data Structure
C++ and Data Structure
Algorithms
1. ADDRESS
2. POINTERS
3. ARRAYS
4. ADDRESS OF EACH ELEMENT IN AN ARRAY
5. ACCESSING & MANIPULATING AN ARRAY USING
POINTERS
6. ANOTHER CASE OF MANIPULATING AN ARRAY USING
POINTERS
7. TWO-DIMENSIONAL ARRAY
8. POINTER ARRAYS
9. STRUCTURES
10. STRUCTURE POINTERS
Chapter 0: C++ LANGUAGE
1. ADDRESS
For every variable there are two attributes:
address and value
cout << "Value of 'y' is: " << y << "\n";
cout << "Address of 'y' is: " << &y << "\n\n";
Chapter 0: C++ LANGUAGE
2. POINTERS
1. is a variable whose value is also an address.
2. A pointer to an integer is a variable that can
store the address of that integer
ia: value of variable
&ia: address of ia
*ia means you are printing the value at the
location specified by ia
Chapter 0: C++ LANGUAGE
int i; //A
int * ia; //B
cout<<"The address of i "<< &i << " value="<<i <<endl;
cout<<"The address of ia " << &ia << " value = " << ia<< endl;
i = 10; //C
ia = &i; //D
Points to Remember
3. ARRAYS
1. An array is a data structure
2. used to process multiple elements with the same data
type when a number of such elements are known.
3. An array is a composite data structure; that means it
had to be constructed from basic data types such as
array integers.
1. int a[5];
2. for(int i = 0;i<5;i++)
1. {a[i]=i; }
Chapter 0: C++ LANGUAGE
a=b; //error
b=a; //OK
Chapter 0: C++ LANGUAGE
7. TWO-DIMENSIONAL ARRAY
int a[3][2];
Chapter 0: C++ LANGUAGE
8. POINTER ARRAYS
You can define a pointer array (similarly to an array of
integers).
In the pointer array, the array elements store the
pointer that points to integer values.
Chapter 0: C++ LANGUAGE
9. STRUCTURES
Structures are used when
you want to process data of
multiple data types
But you still want to refer to
the data as a single entity
Access data:
structurename.membernam
e
Chapter 1: C++ LANGUAGE
1. FUNCTION
2. THE CONCEPT OF STACK
3. THE SEQUENCE OF EXECUTION DURING A
FUNCTION CALL
4. PARAMETER PASSING
5. CALL BY REFERENCE
6. RESOLVING VARIABLE REFERENCES
7. RECURSION
8. STACK OVERHEADS IN RECURSION
9. WRITING A RECURSIVE FUNCTION
10. TYPES OF RECURSION
CHAPTER 2: FUNCTION & RECURSION
1. FUNCTION
– provide modularity to the software
– divide complex tasks into small manageable tasks
– avoid duplication of work
Type of Function: return value &
parameters
On return value
– Void Functions
– Return Function
Example: void display(); int max(int a,int b);
On Parameters
– value parameters
– reference parameters
Exmple: void swap(int &a, int &b); int BinhPhuong(int n);
Week 6: Ôn tập function
Nothing return
void
Week 6: Ôn tập function
Return 1 value
int
–return
Week 6: Ôn tập function
void
–reference parameters
int
On natural way
–return
CHAPTER 2: FUNCTION & RECURSION
3. THE SEQUENCE OF
EXECUTION DURING A
FUNCTION CALL
Result:?
CHAPTER 2: FUNCTION & RECURSION
4. PARAMETER * REFERENCE
PASSING
– passing by value
the value before and after the call remains the same
– passing by reference
changed value after the function completes
CHAPTER 2: FUNCTION & RECURSION
6. RESOLVING VARIABLE
REFERENCES
When a variable can
be resolved by using
multiple references,
the local definition is
given more preference
CHAPTER 2: FUNCTION & RECURSION
7. RECURSION
– A method of
programming
whereby a function
directly or indirectly
calls itself
– Problems: stop
recursion?
CHAPTER 2: FUNCTION & RECURSION
7. RECURSION
CHAPTER 2: FUNCTION & RECURSION
7.
RECURSION:
Hanoi tower
CHAPTER 2: FUNCTION & RECURSION
7. RECURSION
CHAPTER 2: FUNCTION & RECURSION
7 2
1 3 2
1 1 2
1 0
Week3: Recursion Excercises (1)
Print triangle
c d
a b
Week3: Recursion Excercises (8)
7 2
1 3 2
1 1 2
1 0
Week3: Recursion Excercises (9)
Minesweeper
1. String: structure
String
– is array of char
– Ending with null char \0 (size +1)
– Example: store 10 chars:
char str[11];
– “Example”: string const. C/C++ add \0
automayically
1. String: declare
Declare string
– Using array of chars
char str[] = {‘H’,’e’,’l’,’l’,’o’,’\0’}; //declare with null
char str[] = “Hello”; //needn’t null
– Using char pointer
char *str = “Hello”;
1. String: input
Keyboard buffer
char szKey[] = "aaa";
char s[10];
do {
cout<<"doan lai di?";
gets(s);
} while (strcmp (szKey,s) != 0);
puts ("OK. corect");
If user input: aaaaaaaaaaaaa???
1. String: functions
#include <string.h>
strcpy(s1, s2)
strcat(s1, s2)
strlen(s1)
strcmp(s1, s2) -> (-1,0,1)
strchr(s1, ch)
strstr(s1, s2)
char s1[80], s2[80];
cout << "Input the first string: :";
gets(s1);
cout <<1. "Input
String: function
the second examples
string: ";
gets(s2);
cout << "Length of s1= " << strlen(s1);
cout << "Length of s2= " << strlen(s2);
if(!strcmp(s1, s2))
cout << "These strings are equal\n";
strcat(s1, s2);
cout << "s1 + s2: " << s1 << endl;;
strcpy(s1, "This is a test.\n");
cout << s1;
if(strchr(s1, 'e')) cout << "e is in " << s1;
if(strstr(s2, "hi")) cout << "found hi in " <<s2;
2. File: Creating a new file
#include <io.h>
FILE *fp;
fp=fopen(“d:\\test.txt", "wb"))
fwrite(&Address, sizeof(TYPE), count, fp);
fclose(fp);
2.File: Creating a new file
int Arr[3]
#include <io.h>
FILE *fp;
fp=fopen(“d:\\test.txt", “rb"))
while (fwrite(&Address, sizeof(TYPE), count, fp))
{
– …………….
}
fclose(fp);
CHAPTER 0: INTRODUTION
Example:library
– is composed of elements
(books)
– Accessing a particular
book requires knowledge
of the arrangement of the
books
– Users access books only
through the librarian
the logical arrangement of data elements,
combined with
the set of operations we need to access the
elements.
Basic Data Structures
Structures include
– linked lists
– Stack, Queue
– binary trees
What is Algorithm?
Algorithm:
– A computable set of steps to achieve a desired
result
– Ralationship to Data Structure
Example: Find an element
2 4 6
1 3 5 7
1 2 3 4 5 6 7
Sumary
SEARCHING TECHNIQUES and
Complexity of Algorithm
How?
– Proceeds by sequentially comparing the key with
elements in the list
– Continues until either we find a match or the end
of the list is encountered.
– If we find a match, the search terminates
successfully by returning the index of the element
– If the end of the list is encountered without a
match, the search terminates unsuccessfully.
1. LINEAR (SEQUENTIAL) SEARCH
if( flag == 0)
cout<<“ not found”;
}
1. LINEAR (SEQUENTIAL) SEARCH
{find =i;
break;}
return find;
} average time: O(n)
2. BINARY SEARCH
int Search (int list[], int key, int left, int right)
{
if (left <= right) {
int middle = (left + right)/2;
if (key == list[middle])
return middle;
else if (key < list[middle])
return Search(list,key,left,middle-1);
else return Search(list,key,middle+1,right);
}
return -1;
}
3. COMPLEXITY OF ALGORITHMS
Linear Search
– O(n).
Binary Search
– O(log2 N)
Exercise
Exercise:
– Write a small program
Input the number of array
Input array of integer
Display array
Input a value. Using linear search to find position of first
match item in array
– Using 3 function: enterarray, displayarray,linearfind
SORTING TECHNIQUES
Why?
– Do binary search
– Doing certain operations faster
SORTING
SORTING TECHNIQUES
– Start 1 23 2 56 9 8 10 100
– End 1 2 8 9 10 23 56 100
SORTING TECHNIQUES
Average Worst
Bubble sort O(n2) O(n2)
Exchange sort
Insertion sort O(n2) O(n2)
Selection sort O(n2) O(n2)
Quick sort O(nlogn) O(n2)
1.Bubble sort: idea
for(count=0;count<n-1;count++)
for(j=0;j<n-1-count;j++)
if(list[j] > list[j+1])
swap(list[j],list[j+1]);
}
2. Exchange Sorting
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(arr[i] > arr[j])
swap(arr[i],arr[j]);
}
2. Exchange Sorting
Notes:
– on each successive pass, do one less compare,
because the last item from that pass is in place
– if you ever make a pass in which no swap occurs,
the sort is complete
– There are some algorithms to improve
performance but Big O will remain O(n2)
3. Insertion Sort
3 7 5 2 4
take an item from the unsorted list (7) and
insert into the sorted list
sorted unsorted
3 7 5 2 4
take next item from the unsorted list (5) and
sorted unsorted insert into the sorted list
3 5 7 2 4
take next item from the unsorted list (2)
sorted unsorted and insert into the sorted list
2 3 5 7 4
take next item from the unsorted list (4)
sorted unsorted and insert into the sorted list
2 3 4 5 7
3. Insertion Sort
3 7 5 2 4
4. Selection Sort
3 4 5 2 7
biggest last
3 4 5 2 7
3 4 2 5 7
biggest last
3 4 2 5 7
3 2 4 5 7
3 2 4 5 7
2 3 4 5 7
4. Selection Sort
5. Quick Sort: idea
Quick Sort
Pick the leftmost element as the pivot (23). Now , start two cursors (one at either end) going towards the
middle and swap values that are > pivot (found with left cursor) with values < pivot (found with right cursor)
23 17 5 12 19 24 4 43 34 11 3 33 14 26 8 27
swap
23 17 5 12 19 8 4 43 34 11 3 33 14 26 24 27
swap
23 17 5 12 19 8 4 14 34 11 3 33 43 26 24 27
swap
23 17 5 12 19 8 4 14 3 11 34 33 43 26 24 27
swap
Finally, swap the pivot and the value where the cursors passed each other
11 17 5 12 19 8 4 14 3 23 34 33 43 26 24 27
Note : 23 is now in the right place and everything to its left is < 23
and everything to its right is > 23
Quick Sort
Now, repeat the process for the right partition
11 17 5 12 19 8 4 14 3 23 34 33 43 26 24 27
swap
11 17 5 12 19 8 4 14 3
swap
11 3 5 4 19 8 12 14 17
swap
11 3 5 4 8 19 12 14 17
swap
8 3 5 4 11 19 12 14 17
Note: the 11 is now in the right place, and the left partition is all < pivot and the right partition is all > pivot
Quick Sort (worst case)
3 4 5 8 11 12 14 17 19 23 24 26 27 33 34 43
4 5 8 11 12 14 17 19 23 24 26 27 33 34 43
if (j > lower)
quickSort(Arr, lower, j);
if (i < upper)
quickSort(Arr, i, upper);
}
STACKS AND QUEUES
STACKS: concept
QUEUES : concept
STACKS,QUEUES : implement
– Using array
– Using Linked List (next chapter)
1.Stack
#define MAX 10
void main()
{
int stack[MAX];
int top = -1;
push(stack,top, 10 );
pop(stack,top,value);
int value;
cout<<value;
}
1.Stack: implement using array
A circular queue
2.QUEUE: implement using array
#define MAX 10
void main()
{
int queue[MAX];
int bottom,top,count=0;
bottom=top=-1;
enqueue(queue,count,top, 100 );
int value;
dequeue(queue,count,bottom,top,value);
}
2.QUEUE: implement using array
ARRAY
– sequential mapping, elements are fixed distance apart
– makes insertion or deletion at any arbitrary position in an
array a costly operation
Linked List
– not necessary that the elements be at a fixed distance apart
– an element is required to be linked with a previous element
of the list
– done by storing the address of the next element
Array and LINKED LIST
0 1 2 3 4 5 6 X X X X
0 1 2 3 4 5 6 X 7 8 9 X 10 11 X 12 13 14 X 15 16 17 18
Type of Linked List
1 data Link data Link NULL
Link Link
3 data data
Link Link
data
LinkLink
data data 4
LinkLink LinkLink
4 things when building Linked List
1. Structure
– Data element
– Link field element
2. The way to make link between elements
– First, last, middle element
3. How many node to take all list elements, how to take all
list
4. Basic operations:
– Insert new element (every position)
– Delete (every position)
– Find
– Notes: Check value change in step 3
2.Singly Linked List
1. Structure
– Data element
– Link field element
2. The way to make link between elements
– First, last, middle element
3. How many node to take all list elements , how
to take all list
4. Basic operations:
– Insert new element (every location)
– Delete (every position)
– Find
2.Singly Linked List
1. Structure
struct Node
{
int data;
Node *link;
;
}
2.Singly Linked List
Why
•+from pHead, can we list all items?
pHead •+from pHead, can we do everything with list:
insert new, delete?
•+Do we need pTail?
2.Singly Linked List
4. Basic operations:
p data Link data Link NULL
data Link
Remove node
Insert node
void displaylist()
{ Seek Nodes
node *temp=h;
while (temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
2.Singly Linked List: using Phead only
void RemoveNodeatFirst()
{ Remove Node at
if (pHead!=NULL)
{ First
node *t= pHead;
pHead = pHead ->next;
delete t;
}
}
2.Singly Linked List: using Phead only
void removeatlast()
{ Remove Node at
node *t=h;
node *truoc=t; Last
while (t->next!=NULL)
{
truoc=t;
t=t->next;
}
truoc->next=NULL;
delete t;
}
2.Singly Linked List: using Phead only
t->next=newnode;
}
2.Singly Linked List:using pHead &
pTail
data Link
2.Singly Linked List
void removeNodeAtFirst ()
{
If (pHead!=NULL)
{
Node *temp=pHead;
pHead = pHead >next;
delete temp;
}
}
2.Singly Linked List
void removeNodeatLast ()
{
???
}
2.Singly Linked List
Void Display()
{
node *p=pHead;
while (p!=NULL)
{
cout<<p->data<<“ “;
p=p->next;
}
}
2.Singly Linked List
int Count ()
{
int count=0;
node *p=pHead;
while (p!=NULL)
{
count+=1;
p=p->next;
}
return count;
}
2.Singly Linked List
Find node
Single linked list: pHead and pTail
Circular single linked list
Double Linked List
Find Node
Using While
Using Loop
Find Node: using while loop
=========================================
Node* temp; //Node *temp=new Node();???
temp=pHead;
while (temp!=NULL && temp->data!=Xvalue)
temp=temp->next;
May be not found
Find Node: using for loop
data Link
pHead pTail
data Link
pHead pTail
data Link
pHead pTail
pHead pTail
Example:
– Write function to insert at last
– Single linked list with pHead and pTail
4. Circular single linked list
Circular
– Last node point to first node
– Draw like Circle
When using Circular single linked list
– Every node in list had the same position
– Needn’t Head, Tail
4. Circular single linked list
pHead
pHead
Example:
– Write function to remove a node
– Circular single linked list with pHead and pTail
4. Double Linked List
Struct Node
{
Int data;
Node *next;
Node * pre;
};
4. Double Linked List
data
data
data
4. Double Linked List
Example
– Write function to remove first node (pHead)
– Write function to insert a node after another node
Tree
2 9
1 4 8
1. THE CONCEPT OF TREES
Example
1. THE CONCEPT OF TREES
Tree
1. THE CONCEPT OF TREES: Some
terminology
Root
Child (left,right)
Parent
Leaf node
Subtree
Ancestor of a node
Descendant of a node
1. THE CONCEPT OF TREES
BINARY TREE
– no node can have a degree of more than 2.
– The maximum number of nodes at level i will be
2i−1
– If k is the depth of the tree then the maximum
number of nodes that the tree can have is
– 2k − 1 = 2k−1 + 2k−2 + … + 20
2. BINARY TREE AND REPRESENTATION
BINARY TREE
– A full binary tree is a binary of depth k having 2k
− 1 nodes.
– If it has < 2k − 1, it is not a full binary tree
What is the height h of a full tree
with N nodes?
h
2 1 N
h
2 N 1
h log( N 1) O(log N )
The max height of a tree with N nodes is N
(same as a linked list)
The min height of a tree with N nodes is
log(N+1)
2. BINARY TREE AND REPRESENTATION
full binary
3=22-1
7=23-1 15=24-1
2. BINARY TREE AND REPRESENTATION
struct node
{ int data;
node *left;
node *right;
};
Tree traversal
Preorder traversal
– node, left, right
– prefix expression
++a*bc*+*defg
Preorder, Postorder and Inorder
Postorder traversal
– left, right, node
– postfix expression
abc*+de*f+g*+
Inorder traversal
– left, node, right.
– infix expression
a+b*c+d*e+f*g
Preorder, Postorder and Inorder
3. BINARY TREE TRAVERSAL
3. BINARY TREE TRAVERSAL
Inorder = DBEAC
Many trees
4. BINARY SEARCH TREE
But..
– Insert, delete: slow
Important thing: Index in Database system
– Using the right way of Index property
Search Algorithm TreeSearch(k, v)
if (v ==NULL)
return v
To search for a key k, we if k key(v)
trace a downward path
starting at the root return TreeSearch(k, T.left(v))
else if k key(v)
The next node visited
depends on the outcome return v
of the comparison of k with else { k key(v) }
the key of the current node return TreeSearch(k, T.right(v))
If we reach a leaf, the key
is not found and we return 6
nukk
Example: find(4): 2 9
– Call TreeSearch(4,root)
1 4 8
Insertion
6
To perform operation inser(k,
o), we search for key k (using 2 9
TreeSearch)
Assume k is not already in the 1 4 8
tree, and let let w be the leaf
reached by the search
We insert k at node w and w
expand w into an internal node 6
Example: insert 5 2 9
1 4 8
w
5
4. BINARY SEARCH TREE
traverse node
void preorder(node* r)
{
if (r!=NULL)
{ cout<<r->data<<" ";
inorder(r->l);
inorder(r->r);
}
}
4. BINARY SEARCH TREE
traverse node
4. BINARY SEARCH TREE
traverse node
Exercise 1
Search node
Count
– Even/Odd
– Leaf
Sum
– Even/Odd
Height
Delete node
1. SEACRCHING NODE
node* search(node* &r, int data)
{
if (r==NULL)
return NULL;
else
if (r->data==data)
return r;
else
if (data<r->data)
return search (r->l,data);
else
if (data>r->data)
return seach(r->r,data);
}
1. SEACRCHING NODE H3
100
node* search(node* &r, int data)
{
if ( (r==NULL) || (r->data==data) ) H20 H40
return r;
else
if (data<r->data)
return search (r->l,data);
H20 H40
else
if (data>r->data) 80 120
return seach(r->r,data);
Node* S=search(r,80)
}
2. COUNTING THE NUMBER OF
NODES
}
3. Sum of all nodes
int counteven(node* r)
{
if (r!=NULL)
if (r->data%2==0)
return 1+ counteven(r->l)+counteven(r->r);
else
return counteven(r->l)+counteven(r->r);
else
return 0;
}
5. SUM OF EVEN (ODD) NODES
int counteven(node* r)
{
if (r!=NULL)
if (r->data%2==0)
????????????????????
else
????????????????????
else
return 0;
}
6. Count number of leaf nodes
Exercise
– Count number of leaf nodes
6. Count number of leaf nodes
int countleaf(node* r)
{
if (r!=NULL)
if (r->l==NULL && r->r==NULL)
return 1;
else
return countleaf(r->l)+countleaf(r->r);
else
return 0;
}
6. Count number of node had 1 child
int count1child(node* r)
{
if (r!=NULL)
if (????????????????????????????)
return 1+count1child(r->l)+count1child(r->r);
else
return count1child(r->l)+count1child(r->r);
else
return 0;
}
6. Count number of node had 2
children
int count2child(node* r)
{
if (r!=NULL)
if (????????????????????????)
return 1+count2child(r->l)+count2child(r->r);
else
return count2child(r->l)+count2child(r->r);
else
return 0;
}
7. Find height of tree
Deletion of a Node
with No Child
– Set the left of y to
NULL
– Dispose of the node
pointed to by x