Data Structures
Data Structures
Algorithms
Week1
Contents
Textbook
Grade
Software
Textbook
C
Grade
Midterm
test (Lab)
Final test (Lab)
Project (working on group)
Multiple choice test
How to Grade
Grade
BC++, TC++
C-Free is a professional C/C++ integrated
development environment (IDE) that support multicompilers. Use of this software, user can edit, build,
run and debug programs freely.
With C/C++ source parser included
Lightweight C/C++ development tool.
http://www.programarts.com/cfree_en/
CHAPTER 0: INTRODUTION
What
is Data Structures?
Atomic Variables
Atomic
a time.
int num;
float s;
A value
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.
include
linked lists
Stack, Queue
binary trees
and others
What is Algorithm?
Algorithm:
Find an element
2
1
1
4
3
6
5
7
6
Sumary
Chapter 0: C LANGUAGE
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
ADDRESS
POINTERS
ARRAYS
ADDRESS OF EACH ELEMENT IN AN ARRAY
ACCESSING & MANIPULATING AN ARRAY USING
POINTERS
ANOTHER CASE OF MANIPULATING AN ARRAY USING
POINTERS
TWO-DIMENSIONAL ARRAY
POINTER ARRAYS
STRUCTURES
STRUCTURE POINTERS
Chapter 0: C LANGUAGE
1.
ADDRESS
For every variable there are two attributes:
address and value
In memory with address 3: value: 45.
In memory with address 2: value "Dave"
Chapter 0: C LANGUAGE
2. POINTERS
1.
2.
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
cout<<"after assigning value:"<<endl;
cout<<"The address of i "<< &i << " value="<<i <<endl;
cout<<"The address of ia " << &ia << " value = " << ia<< " point to: "<< *ia;
Chapter 0: C LANGUAGE
Points to Remember
Pointers give a facility to access the value of
a variable indirectly.
You can define a pointer by including a *
before the name of the variable.
You can get the address where a variable is
stored by using &.
Chapter 0: C LANGUAGE
3. ARRAYS
1.
2.
3.
int a[5];
for(int i = 0;i<5;i++)
1.
{a[i]=i; }
Chapter 0: C LANGUAGE
4. ADDRESS OF EACH ELEMENT IN AN
ARRAY
Each element of the array has a memory
address.
void printdetail(int a[])
{
for(int i = 0;i<5;i++)
{
cout<< "value in array << a[i] << at address: << &a[i]);
}
Chapter 0: C LANGUAGE
5. ACCESSING & MANIPULATING AN
ARRAY USING POINTERS
Chapter 0: C LANGUAGE
6. ANOTHER CASE OF MANIPULATING AN
ARRAY USING POINTERS
The array limit is a pointer constant : cannot
change its value in the program.
int a[5];
int *b;
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
Chapter 0: C LANGUAGE
9. STRUCTURES
Chapter 1: C LANGUAGE
10. STRUCTURE POINTERS
Process the structure using a structure pointer
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
FUNCTION
provide modularity to the software
divide complex tasks into small manageable tasks
avoid duplication of work
THE SEQUENCE OF
EXECUTION DURING A
FUNCTION CALL
Result:?
passing by reference
changed
RECURSION
A method of
programming
whereby a function
directly or indirectly
calls itself
Problems: stop
recursion?
RECURSION
RECURSION:
Hanoi tower
RECURSION
OF RECURSION
LINEAR RECURSION
TAIL RECURSION
BINARY RECURSION
EXPONENTIAL RECURSION
NESTED RECURSION
MUTUAL RECURSION
OF RECURSION
LINEAR RECURSION
only
OF RECURSION
TAIL RECURSION
Tail
OF RECURSION
BINARY RECURSION
Some
OF RECURSION
EXPONENTIAL RECURSION
An
OF RECURSION
EXPONENTIAL RECURSION
OF RECURSION
NESTED RECURSION
In
OF RECURSION
MUTUAL RECURSION
A recursive
itself.
Some recursive functions work in pairs or even larger
groups. For example, function A calls function B which
calls function C which in turn calls function A.
OF RECURSION
MUTUAL RECURSION
Exercises 1: Recursion
Exercises 2: Recursion
Convert
7
1
2
3
1
2
1
E3(b).
S=a[0]+a[1]+a[n-1]
A:
triangle
c
2
3
1
2
1
Week 3
CHAPTER 3: SEARCHING TECHNIQUES
1. LINEAR (SEQUENTIAL) SEARCH
2. BINARY SEARCH
3. COMPLEXITY OF ALGORITHMS
SEARCHING TECHNIQUES
To finding
unordered list:
linear
an ordered list
binary
2.
List
BINARY SEARCH
Baba?
Eat?
3. COMPLEXITY OF ALGORITHMS
3. COMPLEXITY OF ALGORITHMS
It is generally written as
O(1) --- Constant time --- the time does not change in response to
the size of the problem.
O(n) --- Linear time --- the time grows linearly with the size (n) of
the problem.
O(n2) --- Quadratic time --- the time grows quadratically with the
size (n) of the problem. In big O notation, all polynomials with the
same degree are equivalent, so O(3n2 + 3n + 7) = O(n2)
O(logn) -- Logarithmic time
O(n!)
O(2n)
3. COMPLEXITY OF ALGORITHMS
Example1:
complexity of an algorithm
2 * O(1)? + O(N)
O(N)
?
3. COMPLEXITY OF ALGORITHMS
Example2:
complexity of an algorithm
2
2 * O(1) + O(N)+O(N
?
)
O(N2)
?
3. COMPLEXITY OF ALGORITHMS
Linear
Search
O(n).
Binary
Search
O(log2 N)
Week4: (Chapter 4)
20
test
Week4: (Chapter 4)
SORTING TECHNIQUES
Why?
Do binary search
Doing certain operations faster
SORTING
Week4: (Chapter 4)
SORTING TECHNIQUES
Start 1 23 2 56 9 8 10 100
End 1 2 8 9 10 23 56 100
Week4: (Chapter 4)
SORTING TECHNIQUES
Bubble
Bubble sort
Insertion sort
Selection sort
Exchange sort
Quick sort
Week4: (Chapter 4)
SORTING TECHNIQUES
Average
Worst
Bubblesort
O(n2)
Exchangesort
O(n2)
Insertionsort
O(n2)
O(n2)
Selectionsort O(n2)
O(n2)
Quicksort
O(n2)
O(nlogn)
compare3and7;7is>3soadvance
compare7and5,7>5soswapthem
compare7and2,7>4soswapthem
compare7and4,7>4soswapthem
Endofpass1;noticethat7isintherightplace
sorting algorithm
Idea:
What
happens?
DEMO
2. Exchange Sorting
Method
2. Exchange Sorting
void Exchange_sort(int arr[], int n)
{
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(arr[i] > arr[j])
swap(arr[i],arr[j]);
}
DEMO
2. Exchange Sorting
Notes:
3. Insertion Sort
Strategy:
3. Insertion Sort
sorted
unsorted
sorted
3
unsorted
7
unsorted
5
unsorted
5
takenextitemfromtheunsortedlist(2)
andinsertintothesortedlist
sorted
2
takenextitemfromtheunsortedlist(5)and
insertintothesortedlist
sorted
2
takeanitemfromtheunsortedlist(7)and
insertintothesortedlist
unsorted
sorted
3
takenextitemfromtheunsortedlist(4)
andinsertintothesortedlist
3. Insertion Sort
void insertionSort(int arr[], int n){
int j, key;
for(int i = 1; i < n; i++){
key = arr[i];
j = i - 1;
while(j >= 0 && arr[j] > key)
{ arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
3. Insertion Sort
Note
4. Selection Sort
Strategy:
biggest
4. Selection Sort
last
biggest last
biggest last
4. Selection Sort
void selection_sort(int arr[], int n)
{int i, j, min;
for (i = 0; i < n - 1; i++)
{
min = i;
for (j = i+1; j < n; j++)
{ if (list[j] < list[min]) min = j; }
swap(arr[i],arr[min]);
}
}
4. Selection Sort
Notice
5. Quick Sort
5. Quick Sort
Sorting
5. Quick Sort
Another divide-and-conquer sorting algorihm
To understand quick-sort, lets look at a high-level description of
the algorithm
1) Divide : If the sequence S has 2 or more elements, select an
element x from S to be your pivot. Any arbitrary element, like
the last, will do. Remove all the elements of S and divide them
into 3 sequences:
Quick Sort
Picktheleftmostelementasthepivot(23).Now,starttwocursors(oneateitherend)goingtowardsthe
middleandswapvaluesthatare>pivot(foundwithleftcursor)withvalues<pivot(foundwithrightcursor)
23
17
12
19
24
43
34
11
33
14
26
27
swap
23
17
12
19
43
34
11
33
14
26
24
27
33
43
26
24
27
34
33
43
26
24
27
swap
23
17
12
19
14
34
11
swap
23
17
12
19
14
11
swap
Finally,swapthepivotandthevaluewherethecursorspassedeachother
11
17
12
19
14
23
34
33
43
Note:23isnowintherightplaceandeverythingtoitsleftis<23
andeverythingtoitsrightis>23
26
24
27
Quick Sort
Now,repeattheprocessfortherightpartition
11
17
12
19
14
14
12
14
17
14
17
23
34
33
43
26
24
27
swap
11
17
12
19
swap
11
19
swap
11
19
12
swap
8
11
19
12
14
17
Note:the11isnowintherightplace,andtheleftpartitionisall<pivotandtherightpartitionisall>pivot
11
12
14
17
19
23
24
26
27
33
34
43
19
23
24
26
27
33
34
43
Thereisnothingtoswap
4
11
12
14
17
Again,nothingtoswap..
Thepartitionsarealwaysthemaximumsizeandtheperformance
degradestoO(n2)
Quick
Sort
void quickSort(int Arr[], int lower, int upper)
{
int x = Arr[(lower + upper) / 2];
int i = lower; int j = upper;
do{
while(Arr[i] < x) i ++;
while (Arr[j] > x) j --;
if (i <= j)
{
swap(Arr[i], Arr[j]);
i ++; j --; }
}while(i <= j);
if (j > lower)
quickSort(Arr, lower, j);
if (i < upper)
quickSort(Arr, i, upper);
}
Kim tra 15
S dng hm hp l.
Ch : li syntax
loop with ;
int sum = 0;
for (i=1;i<=n;i++)
sum+=i;
cout <<"Sum="<<sum;
int sum = 0;
for (i=1;i<=n;i++)
sum+=i;
cout <<"Sum="<<sum;
int i, flag = 0;
for(i=0;i<n;i++)
if( arr[i] == element)
{ flag =1;
cout<<"tim thay o vi tri: "<<i;
break;
}
else
cout<<"khong tim thay";
concept
QUEUES : concept
STACKS,QUEUES : implement
Using array
Using Linked List (next chapter)
1.Stack
LIFO
1.Stack
Managing
Top element
2.QUEUE
FIFO
A circular queue
Expression evaluation
Queue:
priority queues
Exercise:
Implement:
5 sort algorithms
Implement stack, queue using array
Week 6: n tp function
On
return value
Void Functions
Return Function
Example:
On
Parameters
value parameters
reference parameters
Exmple:
Week 6: n tp function
Nothing
return
void
Week 6: n tp function
Return
1 value
int
return
Week 6: n tp function
Return
many value
void
int
reference
parameters
On natural way
return
Week 6: n tp function
Example
ARRAY
Linked List
X 10 11 X 12 13 14 X 15 16 17 18
data
data
Link
Link
data
data
Link
Link
NULL
Link
Link
data
data
Link
Link
data
LinkLink
data
data
LinkLink
LinkLink
1. Structure
Data element
Link field element
First, last, middle element
3. How many node to take all list elements, how to take all
list
4. Basic operations:
Link
Data element
Link field element
data
1. Structure
Link
NULL
Structure
struct Node
{
int data;
Node *link;
a.data=10;
a.link=NULL;
cout<<a.data;
b->data=20;
b->link=NULL;
cout<<b->data;
delete b;
data Link
Head
data Link
Middle
data Link
data Link
Last
NULL
data Link
data Link
data Link
data Link
pTail
NULL
Why
+from pHead, can we list all items?
pHead
data Link
data Link
data Link
pTail
data Link
pHead
NULL
Basic operations:
data Link
data Link
data Link
NULL
Remove node
Insert node
creating new node
Node * createNewNode(int X)
{
Node *p=new Node;
If (p!=NULL)
{
p->data=X;
p->link=NULL;
}
return p;
p
data Link
NULL
Node at First
Seek Nodes
Remove Node at
First
Find Node
Remove Node at
Last
Insert Node at
Last
pTail
data Link
data Link
data Link
NULL
void removeNodeAtFirst ()
{
If (pHead!=NULL)
{
Node *temp=pHead;
pHead = pHead >next;
delete temp;
}
}
void removeNodeatLast ()
{
???
}
Void Display()
{
node *p=pHead;
while (p!=NULL)
{
cout<<p->data<< ;
p=p->next;
}
}
int Count ()
{
int count=0;
node *p=pHead;
while (p!=NULL)
{
count+=1;
p=p->next;
}
return count;
}
Write a program for buiding single linked list: using pHead only
Display menu
Week 7
Find
node
Single linked list: pHead and pTail
Circular single linked list
Double Linked List
Find Node
Using
While
Using Loop
Add node
Remove Node
pTail is changed?
pTail=NULL
How to check ?
pHead= pTail
data Link
pHead
data Link
pTail
data Link
pTail is changed?
pTail=NULL
How to check ?
pHead= pTail
data Link
pHead
data Link
pTail
data Link
pTail is changed?
pTail=NULL
How to check ?
pHead= pTail
data Link
pHead
data Link
pTail
data Link
data Link
pTail is changed?
Remove node
pHead =
pTail=NULL
pHead= pTail
How to check ?
data Link
pHead
data Link
pTail
data Link
data Link
When
pHead =NULL
pHead
How to check ?
data Link
pHead
data Link
data Link
data Link
steps
data Link
data Link
data Link
data Link
data Link
data Link
data Link
data Link
data Link
data Link
data Link
nodepHead =NULL
pHead
How to check ?
data Link
pHead
data Link
data Link
data Link
};
new node
Remove
node
data
data
data
data
data
data
data
data
data
data
data
node: steps
data
data
data
data
data
data
data
data
data
data
data
Week 8
Exercises
Review: File
Review: String
Excercises
1. String: structure
String
is array of char
Ending with null char \0 (size +1)
Example: store 10 chars:
char
str[11];
1. String: declare
Declare
string
*str = Hello;
1. String: input
char
*gets(char *s);
cin>>s;
1. String: output
int
buffer
If
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)
<io.h>
*fp;
fp=fopen(d:\\test.txt", "wb"))
fwrite(&Address, sizeof(TYPE), count, fp);
fclose(fp);
Arr
for (i=0;i<=3;i++)
Fwrite(&Arr[i], sizeof(int), 1, fp);
#include <io.h>
FILE *fp;
fp=fopen(d:\\test.txt", rb"))
while (fwrite(&Address, sizeof(TYPE), count, fp))
{
}
fclose(fp);
3.Excercises
Exercise
Week 9: Tree
1.
3.
2
1
6
9
Example
not a tree
Tree
Root
Child (left,right)
Parent
Leaf node
Subtree
Ancestor of a node
Descendant of a node
Degree of a Tree
Level of a Node
BINARY TREE
2k 1 = 2k1 + 2k2 + + 20
BINARY TREE
2 1 N
h
2 N 1
h
The
h log( N 1) O (log N )
7=23-1
15=24-1
Tree traversal
inorder (LDR )
Postorder (LRD )
preorder (DLR )
Pre-order traversal
traversal
traversal
Inorder
traversal
Inorder = DBEAC
Many trees
search tree
search tree.
Performance
But..
Important
Search
AlgorithmTreeSearch(k, v)
if(v==NULL)
returnv
To search for a key k, we
if kkey(v)
trace a downward path
returnTreeSearch(k, T.left(v))
starting at the root
else if kkey(v)
The next node visited
returnv
depends on the outcome
else{kkey(v)}
of the comparison of k with
the key of the current node
returnTreeSearch(k, T.right(v))
If we reach a leaf, the key
6
is not found and we return
nukk
2
9
Example: find(4):
Call TreeSearch(4,root)
Insertion
w
6
2
1
9
4
8
5
new node
Insert node
Insert node
Insert Order
node
void preorder(node* r)
{
if (r!=NULL)
{ cout<<r->data<<" ";
inorder(r->l);
inorder(r->r);
}
}
node
node
Exercise 1
1.
Exercise 2
1.
Exercise 3
1.
Week 10
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
H20
H40
H20
H40
80
120
NULL NULL
NULL NULL
Node* S=search(r,80)
What does S stand for?
sum(node *p)
{
if( p == NULL)
return(0);
else
return( p->data+sum(p->l)+sum(p->r) );
}
Height (node* n)
{
if(n==NULL) return 0;
else return 1+max(Height (n->l)),
Height (n->r));
}
8. Delete node
Divide
into 3 cases
8. Delete node
Deletion
of a Node
with No Child
8. Delete node
Deletion
of a Node with
One Child
8. Delete node
Deletion
8. Delete
node
But WHY???
Deletion (cont.)
1
Example: remove 3
8
6
z
1
5
8
6
Exercise:
Write
Week 13
AVL Tree
15
15
10
10
10
20
3
20
18
13
1
NOT an AVL tree. Why?
AVL trees
23
AVL Tree
BTS
Where did it come from?
Why?
Operation
Insert
Delete
Look up
balance factor
height of its right subtree minus the height of its left subtree
-1
x
nh-1
nh-2
nh-1
nh-1
nh-1
nh-2
Rotations
Rotations
Rotations
Insertion
Insertion
h+3
h+2
h+2
h+2
h+2
Insertion
Why???
Insertion
Deletion
Deletion
Deletion : no rotation
No need to
rotate.
Exercise 1
a. Insert 3
???
a. Insert 3
An: Exercise 1
Exercise 2
a. Insert 5
???
An. Exercise 2
a. Insert 5
Exercise 3
Insertion order:
10, 85, 15, 70, 20, 60, 30, 50, 65, 80, 90, 40, 5, 55
???
An Exercise 3
Insertion order:
10, 85, 15, 70, 20, 60, 30, 50, 65, 80, 90, 40, 5, 55
Exercise 4
Delete 40
An. Exercise 4
Delete 40
An. Exercise 4
Delete 40
Exercise 5
Delete 20
An. Exercise 5
Delete 20
Week 14
Sa bi tp
Exercise 1 /S 4
T chc v xy dng 2 hm :
GiiPT_bac1
GiiPT_bac2
a
b
x1
a
c
b
x2
Trng hp
Tnh ng gi?
x
Trng hp
Exercise 3 /S 4
Vit chng trnh tnh lng cho cc cng
nhn ti xng may. Mi cng nhn s c
gi vo v gi ra trong mt ngy. Tin
lng c tnh nh sau:
T 5h-8h: mi gi 20,000
T 8h-11h: mi gi 15,000
T 11h-14h: mi gi 30,000
T 14h-17h: mi gi 22,000
T 17h-24h: mi gi 40,000
Exercise 3 /S 4
11
14
17
24
Exercise 3 /S 4
v1
c1
11
c2
v2
14
Double TinhTien(c1,c2,v1,v2,dongia)
17
24
Exercise 3 /S 4
v1
c1
c2
V2<c1
v2
V2>c1 && v2<c2
V1<c1
11
V2>c2
14
V2<c2
V2>c2
V1>c2
Double TinhTien(c1,c2,v1,v2,dongia)
Bi tp 1 /S 10
Sinh vin:
+M SV: char[10];
+M Lp : int
+Tn SV: char[255];
+DiemToan
+DiemLy
+DiemHoa
Lp gm cc thng tin:
+M Lp: int
+Tn Lp: char[10];
+Kha
1Tree - 1Tree
Struct SV
{
char ma[10];
Ten char[20];
Int malop;
Double toan,ly,hoa;
};
Struct lop
{
int ma;
Ten char[20];
};
1
NCD1A
123
Nguyn Th Nh
Lp: 1
im: 9,8,10
1Tree - 1Tree
Struct lop
{
int ma;
Ten char[20];
Lop* left,right;
};
1
NCD1A
Struct SV
{
char ma[10];
Lop* lop;
Int malop;
Double toan,ly,hoa;
SV* left,right;
};
123
Nguyn Th Nh
Lp: ?
im: 9,8,10
1Tree - nTree
Struct lop
{
int ma;
Ten char[20];
SV *ListSV;
Lop* left,right;
};
1
NCD1A
Struct SV
{
char ma[10];
Double toan,ly,hoa;
SV* left,right;
};
123
Nguyn Th Nh
Lp: ?
im: 9,8,10
Struct lop
{
int ma;
Ten char[20];
SV* listSV;
Lop* left,right;
};
1
NCD1A
Struct SV
{
char ma[10];
Double toan,ly,hoa;
SV* next;
};
123
Nguyn Th Nh
Lp: ?
im: 9,8,10
Struct lop
{
int ma;
Ten char[20];
SV* listSV;
Lop* left,right;
};
1
NCD1A
Struct SV
{
char ma[10];
Double toan,ly,hoa;
SV* next,pre;
};
123
Nguyn Th Nh
Lp: ?
im: 9,8,10
Struct lop
{
int ma;
Ten char[20];
SV* listSV;
Lop* next,pre;
};
1
NCD1A
Struct SV
{
char ma[10];
Double toan,ly,hoa;
SV* next,pre;
};
123
Nguyn Th Nh
Lp: ?
im: 9,8,10
Bi tp ti lp
Qun l mua v hnh khch
V my bay (ID,gi)
Khch(PassID, ten)
Mi khch ch mua 1 v
1Tree-1Tree
1double LL-1Tree
Week 15
Some Final Test questions
Problems only
1
What will be the output of the following
code?
int x, y, z;
x=1; y=2; z=3;
int* a = &x;
*a = y;
cout << x << endl;
1G
What will be the output of the following
code?
int x, y, z;
x=1; y=2; z=3;
int* a = &x;
*a = y;
cout << x << endl;
2
2
After execution of the statement:
char *p = "Stuff";
what would be printed by following statement?
printf("%c",*p+3);
S
V
U
F
u
2G
After execution of the statement:
char *p = "Stuff";
what would be printed by following statement?
printf("%c",*p+3);
int main ()
{
int i, j, *p, *q;
p = &i;
q = &j;
*p = 5;
*q = *p + i;
printf("i = %d, j = %d\n", i, j);
}
i=5 j=10
i = 5, j = 5
i=10, j = 5
Nothing. The program will most likely crash.
3G
int main ()
{
int i, j, *p, *q;
p = &i;
q = &j;
*p = 5;
*q = *p + i;
printf("i = %d, j = %d\n", i, j);
}
i=5 j=10
4
If this code fragment were executed in an otherwise
correct and complete program, what would the output
be?
int a = 3, b = 2, c = 5
if (a > b)
a = 4;
if ( b > c)
a = 5;
else
a = 6;
cout << a < endl;
6
5
4
3
4g
If this code fragment were executed in an otherwise
correct and complete program, what would the output
be?
int a = 3, b = 2, c = 5
if (a > b)
a = 4;
if ( b > c)
a = 5;
else
a = 6;
cout << a < endl;
5
int whatIsIt (int x, int n)
{
if ( n == 1 )
return x;
else
return x * whatIsIt(x, n-1);
}
What is the value returned by whatIsIt(4, 4)?
256
64
4
16
128
5g
int whatIsIt (int x, int n)
{
if ( n == 1 )
return x;
else
return x * whatIsIt(x, n-1);
}
What is the value returned by whatIsIt(4, 4)?
256
#include <iostream.h>
int * f(int * p, int & x)
{ ++x; p = &x; return p; }
int main( )
{
int x = 2, y = 5;
int * p = &y;
int * q = f(p, x);
cout << x << y << *p << *q << endl;
return 0;
}
3355
---------------3553
---------------2553
---------------5553
7g
#include <iostream.h>
int * f(int * p, int & x)
{ ++x; p = &x; return p; }
int main( )
{
int x = 2, y = 5;
int * p = &y;
int * q = f(p, x);
cout << x << y << *p << *q << endl;
return 0;
}
3553
8
Giving code segment:
void mangle_numbers(int &a, int b)
{
int c,d,e;
a = 3;
b = a+2;
c = b++;
d = ++b;
e = a+5;
b *=5;
}
void main()
{ int sum,x=5, y=7;
mangle_numbers(x,y);
sum=x+y;}
After running code segment, value of sum is:
9
---------------8
---------------10
---------------12
8g
Giving code segment:
void mangle_numbers(int &a, int b)
{
int c,d,e;
a = 3;
b = a+2;
c = b++;
d = ++b;
e = a+5;
b *=5;
}
void main()
{ int sum,x=5, y=7;
mangle_numbers(x,y);
sum=x+y;}
After running code segment, value of sum is:
10
9
After the following code:
int i = 2;
int k = 4;
int *p1;
int *p2;
p1 = &i;
p2 = &k;
p1 = p2;
*p1 = 6;
*p2 = 8;
what is the value of i and k
28
---------------42
---------------68
---------------24
9g
After the following code:
int i = 2;
int k = 4;
int *p1;
int *p2;
p1 = &i;
p2 = &k;
p1 = p2;
*p1 = 6;
*p2 = 8;
what is the value of i and k
28
10
If myAge, a, and b are all int variables,
what are their values after this sample
program executes?
myAge = 39;
a = myAge++;
b = ++myAge;
10g
If myAge, a, and b are all int variables,
what are their values after this sample
program executes?
myAge = 39;
a = myAge++;
b = ++myAge;
Part 2: Recursion
6
What does the following program output?
#include <iostream>
int test(int n){
if(n<=0)
return 0;
cout << n;
if(n%2==0)
return 1+test(n-3);
else
return 2+test(n-1);
}
void main(){
cout << endl << test(5) << endl;
}
541
5
---------------541
8
---------------541
7
---------------541
6
6g
What does the following program output?
#include <iostream>
int test(int n){
if(n<=0)
return 0;
cout << n;
if(n%2==0)
return 1+test(n-3);
else
return 2+test(n-1);
}
void main(){
cout << endl << test(5) << endl;
}
541
5
7g
15
8g
Giving code segment:
int f( int n )
{
if ( n==1 )
return 1;
else
return ( f(n-1)+n );
}
Select return result when call:
5151
f(101)?
9g
public int mystery(int k, int n)
{
if (n==k)
return k;
else if (n > k)
else
10g
Suppose that the following function.
int sss(int x) {
if (x % 2 == 0)
return x+1;
else
return (x - 1)*sss(x + 1);
}
10
println(sss(3));
11g
The following function.
println(ttt(7, 3));
12g
The following function.
10
1
A searching algorithm requires at most
100n3log(n) + 25n^5 comparisons to
search an array of n elements. The worstcase time complexity for the algorithm is
O(n^3)
O(n^5)
O(n^3log(n))
O(n^8)
Assume that Algorithm Test has a time complexity O(n^3), and that
Algorithm Compute has time complexity O(n^2). What is the time
complexity of the following algorithm?
Execute Algorithm Test
For 5 trials, execute Algorithm Compute
Execute Algorithm Test
O(n^3)
O(n^2)
O(n^18)
O(n^16)
What does the following code fragment do? (All variables are of type int.)
position1 = -1;
position2 = -1;
for (j = 0; j < 50; j++)
for (i = 0; i < 50; i++)
if (arr[i][j] == searchValue)
{
position1 = i;
position2 = j;
}
It searches the array in row order for the first occurrence of searchValue
It searches the array in row order for the last occurrence of searchValue
It searches the array in column order for the first occurrence of searchValue
It searches the array in column order for the last occurrence of searchValue
listnode* temp;
temp = p;
while (**A**)
**B**;
temp->next = q;
What line of code should replace **B**?
p = p->next;
temp++;
temp = temp.next;
temp = temp ->next;
2
If there is a NodePtr named toDelete whose value points
to a valid node in the list, which of the following
statements would remove the node that follows toDelete
from the list and return that memory to the freestore?
tmp = toDelete -> link;
toDelete -> link = toDelete->link->link;
delete tmp;
tmp = toDelete->link->link;
toDelete -> link = toDelete->link->link;
delete tmp;
3
Which of the following statements is not
true?
Singly linked lists can increase their sizes
faster than arrays can increase their sizes
The singly-linked list does not allow you to
access the nth element in constant time
You can search for and find a value in an
array in constant time.
If you mistakingly mis-assign the head pointer
to NULL, you will lose the entire list
Part 4: BST
AD BGC FE
A
B
C
D