COS2611 EXAM PACK 2022
written by
VarsityC
www.stuvia.com
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Cos2611
EXAM PACK
+27 81 278 3372
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
UNIVERSITY EXAMINATIONS
October/November 2020
COS2611
Programming: Data Structures
70 Marks
3 Hours
This paper consists of 11 pages including Appendix A, B and C (pp 10-11).
Instructions:
1. Answer all questions.
2. The total marks for this examination is 70 marks.
3. The mark for each question is indicated in brackets next to the question.
4. If you do not submit your work on or before the indicated time, for whatever reason,
you will be marked as absent.
5. The code in this exam paper can also be downloaded from myUnisa additional
resource in the Exam code folder.
PLAGIARISM is the presentation by a student of an assignment or piece of work which has in fact
been copied in whole or in part from another student’s work, or from any other source, without due
acknowledgement in the text. Dishonest practices may also amount to criminal offences, such as
fraud, theft and criminal copyright liability. Such dishonest practices include the following: copying
information from another person (e.g. another student’s assignment or portfolio) and submitting
identical work where such work is not the result of teamwork and indicated as such by all participants,
asking someone else to do the work on one’s behalf.
Having another person do the work on your behalf will result in disciplinary action, and
potential suspension or expulsion from the university.
First Examiner:
Mr T Masombuka
Second Examiner: Mr L Aron
GOOD LUCK
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
2
COS2611
October/November 2020
Question 1 Program Analysis [12]
For each of the following questions choose the correct alternative.
1.1. What is the running time of the entire code fragment?
for(int i = 1; i < n; i = i*2)
sum++;
A. O(N)
B. O(N2)
C. O(log N)
D. O(N log N)
E. O(1)
Questions 1.2, 1.3 and 1.4 refer to the following code fragment.
1
2
3
for(int j = 10; j <= n; j++ )
for(int k = 1; k <= n; k++ )
sum++;
4
5
6
for(int p = n; p > 1; p/=2 )
for(int q = n; q >=0; q-- )
sum--;
1.2. How many times is statement 3 executed?
A. O(N)
B. O(N2)
C. O(N3)
D. O(N log N)
E. O(log N)
1.3. How many times is statement 6 executed?
A. O(N)
B. O(N2)
C. O(N3)
D. O(log N)
E. O(N log N)
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
3
COS2611
October/November 2020
1.4. What is the running time of the entire code fragment?
A. O(N)
B. O(N2)
C. O(N3)
D. O(log N)
E. O(N log N)
1.5. An algorithm takes 10 seconds for an input size of 1000. How long will it take for an input
size of 2 000 if the running time is O(N2)?
A. 10s
B. 20s
C. 30s
D. 40s
E. 60s
1.6. An algorithm takes 10 seconds for an input size of 1000. How large a problem can be
solved in 80 seconds if the running time is cubic O(N3)?
A. 800
B. 1250
C. 2000
D. 2500
E. 3000
Question 2 Linked List [8]
The insert function of the class orderedLinkedList does not check if the item to be
inserted is already in the list; that is, it does not check for duplicates. Rewrite the definition of
the insert function so that before inserting the item it checks whether the item to be inserted
is already in the list. If the item to be inserted is already in the list, the function outputs an
appropriate error message.
Use the following header:
template <class Type>
void insert(const Type& newItem)
See Appendix A for orderedLinkedList class
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
4
COS2611
October/November 2020
Question 3 Searching [7]
3.1 The Binary Search algorithm uses two index variables first and last to determine the position
(stored in another index variable mid) to search for an element. Copy, compile and run the
code below to generate the values of myList and X (or run myList.cpp). Capture the
screenshot of the output and submit it.
(1)
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
void print(std::vector<int> const &v)
{
for (int i: v) {
std::cout << i << ' ';
}
}
int main()
{
const int N = 7;
vector<int> myList;
set<int> a;
srand( time( 0 ) );
while ( a.size() < N ) a.insert( rand() % 200 );
for ( auto e : a ) //cout << e << ' ';
myList.push_back(e);
cout<<"myList values are:\t";
print(myList);
//get X
int X = rand()%7;
if(X==3)
X++;
cout<<"\n X is: " <<myList[X]<<endl;
}
3.2 Using Binary Search to search for the element X in myList, give the values of
myList[first], myList[mid] and myList[last] (in the form of a table) every time
a new value is calculated for mid.
(6)
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
5
COS2611
October/November 2020
Question 4 Stack and Queues [16]
4.1 Write a recursive function template, isReversedQ that checks whether the contents of
the queue Q and the stack S are the same but reversed. If that is the case, the function
should return the Boolean value true or false otherwise. See the figure below.
m
a
d
d
Stack top
a
Queue front
m
Use the following header:
template <class Type>
bool isReversedQ (stackType <Type> S, queueType <Type> Q);
You may use any member function of class stackType and queueType given in
appendix B and C respectively.
(8)
4.2 Stacks are ideal for checking if parentheses match in an expression. For example the
expression ((a + b)*(c +d) – 7)*8 is balanced while (a+b)*c) is not. Given an
expression as a string, for every ‘(’ character a stack is pushed and popped for every ‘)’.
Using the header:
bool checkParens(const string & s)
Write a C++ function checkParens that implements the above solution.
Hint: To determine the size of the string s use s.length(). You may use any member
function of class stackType given in appendix B.
(8)
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
6
COS2611
October/November 2020
Question 5 Trees [10]
5.1 Copy, compile and run the code below that will generate the inorder and preorder traversals
of a binary tree (or run binaryTree.cpp). Capture the screenshot of the output and submit
it.
(1)
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>
void print(std::vector<int> const &v)
{
for (int i: v) {
std::cout << i << ' ';
}
}
int main()
{
std::vector<int> v = { 10, 20, 30, 40, 50, 60, 70, 80 };
std::cout<<"Inorder:\t";
print(v);
std::cout<<std::endl;
// get a time-based seed
unsigned seed = std::chrono::system_clock::now()
.time_since_epoch()
.count();
shuffle (v.begin(), v.end(), std::default_random_engine(seed));
std::cout<<"Preorder:\t";
print(v);
std::cout<<"\n\nDraw the binary tree\n\n";
return 0;
}
5.2 Use the inorder and preorder numbers from the program to draw the resulting binary tree.
(9)
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
7
COS2611
October/November 2020
Question 6 Sorting [7]
6.1 Copy, compile and run the code below that will generate a list of numbers (Or run
QuicksortList.cpp). Capture the screenshot of the output and submit it.
(1)
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>
#include <set>
using namespace std;
void print(vector<int> const &v)
{
for (int i: v) {
cout << i << ' ';
}
cout<<endl;
}
int main()
{
const int N = 6;
vector<int> unsorted;
set<int> a;
srand( time( 0 ) );
while ( a.size() < N ) a.insert( rand() % 50 );
for ( auto e : a ) //cout << e << ' ';
unsorted.push_back(e);
// get a time-based seed
unsigned seed = std::chrono::system_clock::now()
.time_since_epoch()
.count();
shuffle (unsorted.begin(), unsorted.end(),
std::default_random_engine(seed));
cout<<"\Sort the following list\n\n";
print(unsorted);
return 0;
}
6.2 Sort the list in 6.1 using Quicksort algorithm with the middle element as pivot. Show the
state of the list after each call to the partition procedure.
Indicate the pivots in each list,
the list to be sorted next, and
the sorted list.
(6)
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
8
COS2611
October/November 2020
Question 7 Graphs [10]
7.1 Copy, compile and run the code below that will generate values for a, b and c for the graph
below (Or run graph.cpp). Note the values of a, b, and c in the graph below. Capture the
screenshot of the output and submit it.
(1)
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>
#include <set>
using namespace std;
int main()
{
const int N = 3;
vector<int> graph_abc;
set<int> a;
srand( time( 0 ) );
while ( a.size() < N ) a.insert( rand() % 15 );
for ( auto e : a ) //cout << e << ' ';
graph_abc.push_back(e);
// get a time-based seed
unsigned seed = std::chrono::system_clock::now()
.time_since_epoch()
.count();
shuffle (graph_abc.begin(), graph_abc.end(),
std::default_random_engine(seed));
cout <<"Here are your values\n\n";
cout <<"a is "<< graph_abc[0] <<endl;
cout <<"b is "<< graph_abc[1] <<endl;
cout <<"c is "<< graph_abc[2] <<endl;
}
a
c
0
b
1
3
2
4
2
4
2
1
5
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
9
COS2611
October/November 2020
7.2 Fill in the values of a, b and c from 7.1 in the above graph. Use the shortest path algorithm
to find the shortest distance from node 0 to every other node of the graph below. Give only
the contents of the arrays smallestWeight and weightFound for each iteration of the
algorithm. Complete the table below. Do not redraw the graph.
(9)
Node 0
Node 1
Node 2
Node 3
Node 4
Node 5
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
10
COS2611
October/November 2020
Appendix A
struct nodeType
{
int info;
nodeType *link;
};
template <class Type>
class linkedListType
{
public:
void initializeList();
bool isEmptyList() const;
int length() const;
void destroyList();
Type front() const;
Type back() const;
};
template <class Type>
class orderedLinkedList: public linkedListType<Type>
{
public:
bool search(const Type& searchItem) const;
void insert(const Type& newItem);
void insertFirst(const Type& newItem);
void insertLast(const Type& newItem);
void deleteNode(const Type& deleteItem);
};
Appendix B
template <class Type>
class stackType
{
public:
void initializeStack();
bool isEmptyStack() const;
bool isFullStack() const;
void push(const Type& newItem);
Type top() const;
void pop();
};
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
11
COS2611
October/November 2020
Appendix C
template <class Type>
class queueType
{
public:
bool isEmptyQueue() const;
bool isFullQueue() const;
void initializeQueue();
Type front() const;
Type back() const;
void addQueue(const Type& queueElement);
void deleteQueue();
private:
int count;
};
©
UNISA 2020
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
SIPHIWE MONGALA (65952790)
COS2611
30/10/2020
Question 1
1.1. C.
1.2. B.
1.3. A.
1.4. B.
1.5. B.
Question 2
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
1.6. C.
template void insert(const Type& newItem)
{
nodeType<Type> *current;
nodeType<Type> *trailCurrent;
nodeType<Type> *newNode;
bool found;
newNode = new nodeType<Type>;
assert(newNode != NULL);
is
newNode->info = newItem;
sh
Th
newNode->link = NULL;
if(first == NULL)
{
first = newNode;
count++;
}
if(newItem < first->info)
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:19:32 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/72353387/65952790-COS2611pdf/
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
{
newNode->link = first;
first = newNode;
}
else
{
current = first;
found = false;
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
while(current != NULL && !found && current->link->info < newItem) //search the
//list
current = current->link;
if(current->info >= newItem)
found = true;
else
{
trailCurrent = current;
current = current->link;
}
if(newNode->link == current->link)
else
{
newNode = current->link;
sh
Th
is
cout << "No Duplicates Allowed"<<endl;
current->info = newItem;
}
if(current == first)
{
newNode->link = first;
first = newNode;
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:19:32 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/72353387/65952790-COS2611pdf/
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
count++;
}
else
{
trailCurrent->link = newNode;
newNode->link = current;
count++;
}
}
Question 3
3.1
3.2
[first]
10
103
182
Th
is
Iteration 1
Iteration 2
Iteration 3
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
}
4.1
[last]
182
182
182
sh
Question 4
[mid]
54
167
182
template <class Type>
bool isReversedQ (stackType S, queueType Q)
{
4.2.
bool checkParens(const string & s)
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:19:32 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/72353387/65952790-COS2611pdf/
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
{
stack<char> exp;
char x;
// Traversing the Expression
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '(' )
{
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
// Push the element in the stack
exp.push(s[i]);
continue;
}
if (exp.empty())
return false;
if (s[i] == ‘)’ )
{
//Pop the stack
exp.pop(s[i]);
continue;
}
is
}
Th
Return (exp.empty());
}
5.1
sh
Question 5
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:19:32 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/72353387/65952790-COS2611pdf/
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
5.2
Question 6
6.1
14 41 30 10 37 48
14 41 48 10 37 30
14 41 48 10 37 30
14 10 48 41 37 30
14 10 30 41 37 48
14 10 30 41 37 48
10 14 30 41 37 48
10 14 30 41 37 48
10 14 30 41 48 37
10 14 30 37 48 41
10 14 30 37 48 41
10 14 30 37 41 48
sh
7.1
Th
Question 7
is
10 14 30 37 41 48
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
6.2 pivot is bold
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:19:32 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/72353387/65952790-COS2611pdf/
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
7.2 0 10 8 9 ∞ ∞
TFFFFF
0 10 8 9 ∞ 12
TFTFFF
0 10 8 9 ∞ 10
TFTTFF
0 10 8 9 12 10
TTTTFF
0 10 8 9 12 10
0 10 8 9 12 10
sh
Th
is
TTTTTT
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
TTTTTF
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:19:32 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/72353387/65952790-COS2611pdf/
Powered by TCPDF (www.tcpdf.org)
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
UNIVERSITY EXAMINATIONS
May/June 2020
COS2611
Programming: Data Structures
70 Marks
3 Hours
This paper consists of 10 pages including Appendix A, B and C (pp 9-10).
Instructions:
1. Answer all questions.
2. The total marks for this examination is 70 marks.
3. The mark for each question is indicated in brackets next to the question.
4. If you do not submit your work on or before the indicated time, for whatever reason,
you will be marked as absent. In that case, you will be automatically deferred to the
October/November 2020 examination.
5. The code in this exam paper can also be downloaded from myUnisa additional
resource in Exam code folder.
PLAGIARISM is the presentation by a student of an assignment or piece of work which has in fact
been copied in whole or in part from another student’s work, or from any other source, without due
acknowledgement in the text. Dishonest practices may also amount to criminal offences, such as
fraud, theft and criminal copyright liability. Such dishonest practices include the following: copying
information from another person (e.g. another student’s assignment or portfolio) and submitting
identical work where such work is not the result of teamwork and indicated as such by all participants,
asking someone else to do the work on one’s behalf.
Having another person do the work on your behalf will result in disciplinary action, and
potential suspension or expulsion from the university.
First Examiner:
Mr T Masombuka
Second Examiner: Mr L Aron
GOOD LUCK
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
2
COS2611
May/June 2020
Question 1 Program Analysis [10]
For each of the following questions choose the correct alternative.
Questions 1.1, 1.2 and 1.3 refer to the following code fragment.
1
2
3
for(int j = 10; j <= n; j++ )
for(int k = 1; k <= n; k*=2 )
sum++;
4
5
6
for(int p = n; p > 1; p/=2 )
for(int q = 0; q < 500; q+=4 )
sum--;
1.1. How many times is statement 3 executed?
A. O(N)
B. O(N2)
C. O(N3)
D. O(N log N)
E. O(log N)
1.2. How many times is statement 6 executed?
A. O(N)
B. O(N2)
C. O(N3)
D. O(log N)
E. O(N log N)
1.3. What is the running time of the entire code fragment?
A. O(N)
B. O(N2)
C. O(N3)
D. O(log N)
E. O(N log N)
1.4. An algorithm takes 90 seconds for an input size of 100. How long will it take for an input
size of 10 000 if the running time is O(log n)?
A. 100s
B. 108s
C. 180s
D. 360s
E. 900s
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
3
COS2611
May/June 2020
1.5. An algorithm takes 4 seconds for an input size of 8. How large a problem can be solved
in 64 seconds if the running time is quadratic O(n2)?
A. 8
B. 16
C. 32
D. 68
E. 132
Question 2 Linked List [8]
Implement the operation shareList, which is part of class unorderedLinkedList (See
appendix A). This operation copies the elements of Orig list into listA and listB. All
elements in the even position (elements in position: 0, 2, 4, etc) are copied to listA and the
one’s in an odd position (elements in position: 1, 3, 5, etc) are copied to listB.
Use the following header:
template <class Type>
void shareList(const unorderedLinkedList<Type> & Orig,
unorderedLinkedList<Type> & listA, unorderedLinkedList<Type> &
listB);
Question 3 Searching [6]
Consider the sorted array myList of integers below.
2
5
21
25
35
40
45
48
70
75
89
99
The Binary Search algorithm uses two index variables first and last to determine the position
(stored in another index variable mid) to search for an element. Using Binary Search to search
for the element 75 in myList, give the values of myList[first], myList[mid] and
myList[last] (in the form of a table) every time a new value is calculated for mid.
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
4
COS2611
May/June 2020
Question 4 Stacks [10]
This question must be completed on the IDE.
4.1 L={anbbn} where n ≥1, is a language of all words with the following properties:
The words are made up of strings of a’s followed by b’s.
The number of a’s is always equal to the number of b’s plus one b.
Examples of words that belong to L are
abb, where n=1;
aabbb, where n=2;
aaabbbb, where n=3;
aaaabbbbb, where n=4.
One way to test if a word w belong to this language is to use a stack to check if the number of a’s
balances the number of b’s. Use the provided header and write a function isInLanguageL that uses
a stack to test if any word belongs to L.
bool isInLanguageL (string w)
(8)
4.2 Copy the code below into the IDE to test your isInLanguageL function. (Or open
isLanguage.cpp for the code.). Run the program and submit the screen dump showing
the code and the output on one screen.
#include <iostream>
#include "myStack.h"
#include <string>
using namespace std;
bool isInLanguageL (string w)
{
//Insert your 4.1 code here
}
int main()
{
string a="aaaabbbbb";
string b="aaababbbbb";
string c="aaaabbbbba";
string s1 = isInLanguageL(a) ? " is ACCEPTED" : " is REJECTED";
string s2 = isInLanguageL(b) ? " is ACCEPTED" : " is REJECTED";
string s3 = isInLanguageL(c) ? " is ACCEPTED" : " is REJECTED";
cout << a + s1 <<endl;
cout << b + s2 <<endl;
cout << c + s3 <<endl;
}
return 0;
You may use any of the member functions of class stackType (See appendix B). Note that
this function is not a member of class stackType.
(2)
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
5
COS2611
May/June 2020
Question 5 Queues [8]
Write a recursive function template, identicalQ that checks whether two queues provided
as parameters are identical. If that is the case, the function should return the Boolean value
true or false otherwise. Use the following header:
template <class Type>
bool identicalQ (queueType <Type> Q1, queueType <Type> Q2);
You may use any member function of class queueType given in appendix C.
Question 6 Trees [10]
Consider the following inorder and preorder binary tree traversals:
Inorder: 10, 20, 30, 40, 50, 60, 70, 80, 90
Preorder: 60, 30, 10, 20, 40, 50, 70, 80, 90
Draw the binary search tree.
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
6
COS2611
May/June 2020
Question 7 Sorting [8]
7.1 Copy, compile and run the code below that will generate a list of numbers (Or run
Quicksortgenerator.cpp). Capture the screenshot of the output and submit it.
(2)
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
const int AMOUNT=7; //amount of random numbers that need to be generated
const int MAX=100; //maximum value
int value[AMOUNT]; //array to store the random numbers in
srand(time(NULL)); //always seed your RNG before using it
//generate random numbers:
for (int i=0;i<AMOUNT;i++)
{
bool check; //variable to check or number is already used
int n; //variable to store the number in
do
{
n=rand()%MAX+1;
//check or number is already used:
check=true;
for (int j=0;j<i;j++)
if (n == value[j]) //if number is already used
{
check=false; //set check to false
break; //no need to check the other elements of value[]
}
} while (!check); //loop until new, unique number is found
value[i]=n; //store the generated number in the array
}
cout <<"Your numbers are:\n\n";
for(int i=0; i<AMOUNT; i++)
cout << value[i] <<"\t";
}
cout<<"\n\n";
return 0;
7.2 Sort the list in 7.1 using Quicksort algorithm with the middle element as pivot. Show the
state of the list after each call to the partition procedure.
Indicate the pivots in each list,
the list to be sorted next, and
the sorted list.
(6)
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
7
COS2611
May/June 2020
Question 8 Graphs [10]
8.1 Copy, compile and run the code below that will generate values for a, b and c for the graph
below (Or run graphs.cpp .). Note the values of a, b, and c in the graph below. Capture
the screenshot of the output and submit it.
(2)
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
const int AMOUNT=3; //amount of random numbers that need to be generated
const int MAX=10; //maximum value
int value[AMOUNT]; //array to store the random numbers in
srand(time(NULL)); //always seed your RNG before using it
//generate random numbers:
for (int i=0;i<AMOUNT;i++)
{
bool check; //variable to check or number is already used
int n; //variable to store the number in
do
{
n=rand()%MAX+1;
//check or number is already used:
check=true;
for (int j=0;j<i;j++)
if (n == value[j]) //if number is already used
{
check=false; //set check to false
break; //no need to check the other elements of value[]
}
} while (!check); //loop until new, unique number is found
value[i]=n; //store the generated number in the array
}
cout <<"Here are your values\n\n";
cout <<"a is "<< value[0] <<endl;
cout <<"b is "<< value[1] <<endl;
cout <<"c is "<< value[2] <<endl;
return 0;
}
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
8
COS2611
May/June 2020
0
a
c
b
1
3
2
3
2
10
2
4
8.2 Fill in the values of a, b and c from 8.1 in the above graph. Use the shortest path algorithm
to find the shortest distance from node 0 to every other node of the graph below. Give
only the contents of the arrays smallestWeight and weightFound for each iteration
of the algorithm. Complete the table below. Do not redraw the graph.
(8)
Node 0
Node 1
Node 2
Node 3
Node 4
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
9
COS2611
May/June 2020
Appendix A
struct nodeType
{
int info;
nodeType *link;
};
template <class Type>
class linkedListType
{
public:
void initializeList();
bool isEmptyList() const;
int length() const;
void destroyList();
Type front() const;
Type back() const;
};
template <class Type>
class unorderedLinkedList: public linkedListType<Type>
{
public:
bool search(const Type& searchItem) const;
void insertFirst(const Type& newItem);
void insertLast(const Type& newItem);
void deleteNode(const Type& deleteItem);
void shareList(unorderedLinkedList<Type> & Orig,
unorderedLinkedList<Type> & listA, unorderedLinkedList<Type> & listB);
};
Appendix B
template <class Type>
class stackType
{
public:
void initializeStack();
bool isEmptyStack() const;
bool isFullStack() const;
void push(const Type& newItem);
Type top() const;
void pop();
};
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
10
COS2611
May/June 2020
Appendix C
template <class Type>
class queueType
{
public:
bool isEmptyQueue() const;
bool isFullQueue() const;
void initializeQueue();
Type front() const;
Type back() const;
void addQueue(const Type& queueElement);
void deleteQueue();
private:
int count;
};
©
UNISA 2020
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Questionl
1.1 D
t.2E
1.3 E
t.4c
1.5 C
Question2
Template <class Tyoe>
is
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
Void sharelist (const unorderedLinkedList<Type> & Orig,
unorderedLinkedList<Type> & listA, unorderedLinkedList<Type> & ListB);
node*end=+head;
node*prev=NULL;
node* current=*head
while (end->next !=N ULL)
end=end->*head;
node +new=end;
{
Th
while (current -> data%2!=O currentl=end)
sh
New->next=current;
Current=current->nexU
New=new->nexu
lf (cu rrent-> data%2==O
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:25:38 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/96366760/62055151-COS2611-2020pdf/
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question3
Position
U
1
2
3
4
Values
2
5
2t
25
35
myListlmidl=5
myListlFirstl= 0
5
6
7
40
45
48
myListIlast]=11
8
9
10
77
70
75
89
99
Position
0
7
2
3
4
5
7
8
9
10
11
Values
2
5
2'l-
25
35
40
45
48
myListllastl=11
70
75
89
99
myListlmidl= 8
myListIFirst]=5
0
2
1
Position 0
1
Values
2
5
myListlFirstl=11
0
2
3
27
25
4,1
7
8
9
10
7L
45
40
48
myListllastl=11
70
75
89
99
6
5
6
2
.l
4
5
7
8
9
10
11
21
25
35
40
45
48
mylistIlast]=9
70
7S
89
99
mylistlmidl= 10
1
2
3
4
5
6
7
8
9
10
77
5
27
25
35
40
45
48
70
7:
89
99
mylistlFirstl=9
Question4
4
35
myListlmidl= 10
myListIFirst]=9
Position
Values
2
is
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
Position
Values
6
mYListllastl=9
bool islnLa nguageL (string w)
Th
{
stackType<chaD s;
sh
int index =0;
while(w Iindex]=='3')
{
s.push('X');
index++;
)
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:25:38 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/96366760/62055151-COS2611-2020pdf/
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
while(wlindexl=='bb')
{
if(!s.isEmptyStack0)
{
if(s.top0=='x')
s.pop0;
]
else
index++;
is
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
return false;
return (index == w.size0&& s.isEmptystacko);
sh
Th
)
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:25:38 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/96366760/62055151-COS2611-2020pdf/
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
i!l|lloguagei
siriry a=iaeaabbbbb';
srrxq b.rraaababbbhb{;
is
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
striE r='aaaaltihba';
striu !i = tuIllnlwagel iai
siriog !2 = isinldxg,Dg.l ib)
r:rirg s3 . islli.r.ftiagel ici
rld (1 a - sl ,J,nndl;
sclt (.: b . jl ,{end1'
$!t .1.r c i ,3 i,i$dli
I€hIO:;
Question5
template <class Type>
{
Th
bool identicalQ (queueTypeType<Type> Q1, queueType< Type > Q2)
return true;
sh
if(Ql.isEmptyQueue0 && Q2.isEmptyQueue0)
else if (Ql.lsEmptyQueue0 | | Q2.isEm ptyQueue0)
return false;
else if (Q1.top0 != Q2.top0)
return false;
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:25:38 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/96366760/62055151-COS2611-2020pdf/
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
else
{
Q1.pop0;
Q2.PoP0;
return identicalQ(s1, s2);
)
)
sh
Th
is
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
Question6
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:25:38 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/96366760/62055151-COS2611-2020pdf/
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
QuestionT
7.t
a' -!e,+ma_s\Do', mc-t!'. o@t'B(ii 'quil\'odga '
3
l0
;o t i.t nuc!al!=-';
?4
!2
14
ls
1,i
inr -Yelne:lllogN:I
)
-
l?1
rxecutici iifto : IB lSB s
i
i
t
sraldrr5e Nilill i;
.fi
1e
1!
?3
24
25
26
11
brol riecki
int .;
I
fot iiat j=r;l.ri:i_-l
it (: - viluelrl I
ciEck=f.-1se;
3a
33
3+
35
36
39
tl
I
t
51
3l
i
is
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
21
.:E:\auij
co!. ._- oYo"t is!r:.
foriiat i=r; ilt}roLr$!; i--l
c.Et .. raluei:: 'rl"\irl
.6ut 'o\5\a";
Pivot
Itobe
sh
Th
7.2
I sorted
Sorted
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:25:38 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/96366760/62055151-COS2611-2020pdf/
Want to earn
R1,135 per month?
I
Stuvia.com - The study-notes marketplace
QuestionS
8.1
,. I coEt iEt }}lCtjl.l=:'
j
r1 i
1,i
13 I iat ?eine i}llcu{Tl
let
,'
5
..t!..ed 3 io(o) er"utio' iise : 1'860
5ra.d iitre !{aralr \ ;
15:
," l
r1 I
t3i
int i=:; iri,l{o!1tri i_-r
20 I
bs1 check)
,,}
:
i
,ll
24 I
.,?i
,
I
35
36
3?
3A
33
42
43
8.2
is
ar stu
ed d
vi y re
aC s
o
ou urc
rs e
eH w
er as
o.
co
m
foi iitt j=ii jr:1:l-')
if i. -.: ea1!Eilil
il
34
coqt i{'5e!e sre vlE ',61e5u\rtr:
<<end!'
coui <,lia is r'. va1*i'l
.:endl,
c.ai: r.ib i5 ii. Eheirl
lsl .itc 1s i<': Yaluelti < reartl;
Node 2
0
Node 1
A
T
f
F
o
10
2
T
f
0
Node 0
sw
wf
sw
wf
SW
Node 3
Node 4
F
F
2
;-
T
I
F
10
2
2
*
f
T
F
F
T
0
10
2
7
T
f
T
F
F
wf
SW
0
10
2
?
?
sh
1
Th
wf
T
T
F
F
SW
wf
T
This study source was downloaded by 100000799301222 from CourseHero.com on 10-07-2021 03:25:38 GMT -05:00
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
https://www.coursehero.com/file/96366760/62055151-COS2611-2020pdf/
Powered by TCPDF (www.tcpdf.org)
i
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
COS2611
May/June 2019Memo
QUESTION 1
[10 x 2 = 20]
For each of following questions choose the correct alternative.
1.
An algorithm takes 5 seconds for an input size of 100. If the algorithm is quadratic,
approximately how long does it take to solve a problem of size 200?
A.
B.
C.
D.
E.
2.
Which of the following functions grows fastest?
A.
B.
C.
D.
E.
3.
10 seconds
15 seconds
20 seconds
25 seconds
None of the above
n
n log n
10
log n
n2
What is the running time of the following code fragment?
E.
for(int i = 0; i < n; i++)
for(int j = 0; j < i; j++)
sum++;
A.
B.
C.
D.
E.
4.
O(n2)
O(n3)
O(n4)
O(n5)
None of the above
What is the running time of the following code fragment?
i = n;
while (i >= 1)
{
x = x + 1;
i = i / 2;
}
A. O(n2)
B. O(n3)
[TURN OVER]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
2
C.
D.
E.
5.
COS2611
May / June 2019
O(n4)
O(log n)
O(2n)
What is the running time of the following code fragment?
for(int i =0; i < n; i++)
for(int j = 0; j < n*n; j++)
for(int k = 0; k < 2n*n; k++)
sum++;
A.
B.
C.
D.
E.
O(n4)
O(n2)
O(n log n)
O(n5)
None of the above
Consider the following list where each node is of type nodeType(see appendix A) and then answer
questions 6,7 and 8.
list
18
32
23
43
list -> link ->link ->info == 23
list ->link -> link == p->link
p->link->link->link == q ->link
p -> link->info < q ->info
q ->link -> link -> link == NULL
Which of the following statements will cause p to point to the node containing info 23?.
A.
B.
C.
D.
E.
8.
45
Which of the following relational expressions will return the value FALSE?
A.
B.
C.
D.
E.
7.
25
q
p
6.
87
p = p->link
p = list->link->link
p->info = 23
A and B
A, B and C
What is the output of the following c++ code?
while (p!=NULL){
cout << p->info << “
p = p -> link->link
“;
[TURN OVER]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
3
COS2611
May / June 2019
}
9.
A. 18, 32, 23, 43, 87, 25, 45
B. 32, 43, 25
C. 32, 23, 43, 87, 25, 45
D. run-time error will occur
E. None of the above
A binary search tree is created when elements are inserted in the following order: 3, 5, 2, 1, 6, 4.
Which of the following is a postorder traversal of the binary search tree created?
A.
B.
C.
D.
E.
10.
1, 2, 3, 4, 5, 6
2, 1, 3, 4, 6, 5
1, 2, 4, 6, 5, 3
1, 2, 4, 5, 6, 3
6, 5, 4, 3, 2, 1
Which one of the following statements about Quicksort and Mergesort is not true?
A.
B.
C.
D.
E.
Both Quicksort and Mergesort sort a list by partitioning the list.
In a Quicksort, the sorting work is done during the partitioning of the list.
In a Mergesort, the sorting work is done during the merging of the list.
To partition a list, Mergesort selects an item from the list called the pivot.
Mergesort and Quicksort are recursive algorithms.
QUESTION 2
[8]
Consider the definition of struct nodeType and class linkedListType given in appendix
A and then answer the questions that follow:
2.1
The linked list given below consists of nodes of string type nodetype. Provide code that
will set up the given situation in memory.
adjPtr
"fat"
"thin"
[3]
nodeType<string> * adjptr = new nodeType;
adjPtr->info = “fat”;
adjPtr->link = new nodeType;
adjPtr->link->info =”thin”;
[TURN OVER]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
4
adjPtr->link->link =adjPtr;
2.2
COS2611
May / June 2019
Provide a member function of class linkedListType that determines the minimum
element in a list. Use the following header:
template<class Type>
Type linkedListType<Type>::min()
You can assume that the list is not empty and that operator > and operator < has been
overloaded for Type.
[5]
template<class Type>
Type linkedListType<Type> :: max()
{
Type largest = first -> info;
nodeType<Type> *current:= first-> link;
while( current != NULL)
if (current -> info > largest )
largest = current -> info;
current = current -> link;
}
return largest;
}
QUESTION 3
[10]
Stacks are ideal for checking if parentheses match in an expression. For example the expression
((a + b)*(c +d) – 7)*8 is balanced while (a+b)*c) is not.
Here follows a possible outline for the algorithm, which returns true if a sequence of parentheses in a
string is balanced and false otherwise.
bool checkParens(const string & s)
{
// declare a character stack called mystack
// for each character in a string
{
// if (the character is a '(' )
//
push it on to mystack
// else if (the character is a ')' and mystack is not empty)
//
pop a character off mystack
// else
//
return false
}
// return true
}
3.1
Explain why the outline given above is incorrect. Use the following unbalanced sequence to
justify your answer:
( ( ( ) )
[2]
[TURN OVER]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
5
COS2611
May / June 2019
It produces a false result. First ( ( ( are pushed successively onto the stack. Then the stack is popped twice each time a
) character is encountered. When the end of the string is reached, it is assumed that the string is balanced but there is one
( character still left on the stack. There needs to be a check to determine if the stack is empty after the process.
3.2
Provide a correct and completed version of checkParens() in C++.
Hint: To determine the size of the string s use s.length()
(Refer to Appendix B )
[8]
bool checkParens(const string & s)
{
stackType <char> mystack(10);
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(')
mystack.push(s[i]);
else if (s[i] == ')')
{if(mystack.isEmptyStack())
return false;
mystack.pop();
}
}
if(!mystack.isEmptyStack()){
return false;
}
return true;
}
QUESTION 4
[8]
Write a function removeX that removes all occurrences of an item in a queue without changing the
order of the other elements in the queue. Use the following header:
template < class Object >
void removeX( queueType< Object > & Q, const Object & x )
See Appendix C for the definition of queueType.
template <class Type>
void removeX(queueType<type> & Q, const & X)
{
queueType Q1();
while (!Q.isEmptyQueue() )
{
if (Q.front() != X)
Q1.addQueue(Q.front() ) ;
Q.deleteQueue();
}
while (!Q.isEmptyQueue() )
{
Q.addQueue(Q1.front() );
Q1.deleteQueue();
}
[TURN OVER]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
6
COS2611
May / June 2019
}
QUESTION 5
[10]
Consider the following array of integers:
2, 8, 4, 3, 6, 4
5.1
Sort the array using insertion sort. Show the state of the array after each iteration of the outer loop
of the insertion sort algorithm.
[5]
2
2
2
2
2
8
4
3
3
3
5.2
Sort the array using quicksort. Show the state of the array for each new pivot chosen.
2
3
2
2
2
8
2
3
3
3
4
8
4
4
4
4
4
4
4
4
3
3
8
6
4
6
6
6
8
6
3
4
4
4
4
4
4
4
4
8
6
6
6
6
6
[5]
4
8
8
8
8
Please be carefully when marking this, as the students may have chosen a different pivot, the first or
last element. Please mark accordingly. This solutions choses the middle element as pivot. The solution
may still differ slightly as the student may show more rows than is required.
QUESTION 6
[6]
Consider a recursive function that counts the number of right children in a binary tree. For example 32,
40, 24 and 16 are right children; hence the tree below has 4 right children.
22
14
11
32
16
23
40
24
[TURN OVER]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
7
COS2611
May / June 2019
Provide the implementation for the recursive binary tree method numofRightChildren, which is
defined in the binaryTreeType class that takes as a parameter a pointer to the root node of a binary
tree and returns the number of right children in a binary tree.
//Definition of the node
template<class elemType>
struct nodeType
{
elemType
info;
nodeType<elemType> *llink;
nodeType<elemType> *rlink;
};
//Definition of the class
template <class elemType>
class binaryTreeType
{
public:
int numberofRightChildren()const;
{return numofRightChildren(root);}
//other member functions
protected:
nodeType<elemType> *root;
private:
//other member functions
int numofRightChildren(nodeType<elemType> *p)const;
};
template<class elemType>
int binaryTreeType<elemType>::
numberofRightChildren(binaryTreeNode<elemType> *p) const
{
if (p == NULL)
return 0;
if( p->rlink != NULL)
return numberofRightChildren(p->llink) +
numberofRightChildren(p->rlink) + 1
else
return numberofRightChildren(p->llink);
}
[TURN OVER]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
8
QUESTION 7
[8]
0
4
2
1
1
5
8
COS2611
May / June 2019
7
3
4
2
3
3
5
3
Use the shortest path algorithm to find the shortest distance from node 0 to every other node of the
graph. You are not required to redraw the graph, give only the contents of the arrays
smallestWeight and weightFound for each iteration of the algorithm.
[8]
1 mark each for first 4 iterations , 2 marks each for the last two
0
smallestWeight 0
weightFound
T
1
2
F
2
∞
F
3
∞
F
4
∞
F
5
4
F
0
smallestWeight 0
weightFound
T
1
2
T
2
9
F
3
5
F
4
∞
F
5
3
F
0
smallestWeight 0
weightFound
T
1
2
T
2
9
F
3
5
F
4
11
F
5
3
T
0
smallestWeight 0
weightFound
T
1
2
T
2
8
F
3
5
T
4
10
F
5
3
T
0
smallestWeight 0
1
2
2
8
3
5
4
10
5
3
[TURN OVER]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
9
weightFound
T
T
T
T
F
T
0
smallestWeight 0
weightFound
T
1
2
T
2
8
T
3
5
T
4
10
T
5
3
T
COS2611
May / June 2019
[TURN OVER]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
10
COS2611
May / June 2019
Appendix A
struct nodeType
{
int info;
nodeType *link;
};
template <class Type>
class linkedListType
{
public:
void initializeList();
bool isEmptyList() const;
int length() const;
void destroyList();
Type front() const;
Type back() const;
void deleteSmallest();
};
Appendix B
template <class Type>
class stackType
{
public:
void initializeStack();
bool isEmptyStack() const;
bool isFullStack() const;
void push(const Type& newItem);
Type top() const;
void pop();
};
Appendix C
template <class Type>
class queueType
{
public:
bool isEmptyQueue() const;
bool isFullQueue() const;
void initializeQueue();
Type front() const;
Type back() const;
void addQueue(const Type& queueElement);
void deleteQueue();
private:
int count;
};
©
UNISA 2019
[TURN OVER]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
COS2611 Oct/Nov 2018
Question 1
1C
2C
3D
4A
5B
6C
7D
8E (Can’t see the lines but still no answer kinda makes sense)
9E
10D
Question 2
2.1
nodeType<int> ptr = new nodeType<int>;
ptr->info = 43;
ptr->link = p->link;
p->link = ptr;
2.2
template<class Type>
Type linkedListType<Type>::max()
{
nodeType<Type> current = first->link;
nodeType<Type> max = first;
while(current != NULL)
{
if(current > max)
max = current;
current = current->link;
}
return max->info;
}
Downloaded
by:by:
NkuliMckintosh
| vicdp94@gmail.com
Downloaded
Junerdiki | Junerdiki@gmsil.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 3
3.1.
template<class Type>
bool identicalQ(queueType<Type> Q1, queueType<Type> Q2)
{
while(!Q1.isEmptyQueue() && !Q2.isEmptyQueue && Q1.front() ==
Q2.front())
{
Q1.deleteQueue();
Q2.deleteQueue();
}
return Q1.isEmptyQueue() && Q2.isEmptyQueue();
}
3.2.
i) Queue. Customers arriving first must be served first.
ii) Neither. Both do not support random access of data.
iii)Both. A stack can be used for ‘backspace’. The last deleted character is restored first. A Queue can be
used for the whole line. Characters will be restored in the same order they were when deleted.
iv)Both can do. Stack: Jobs will be stacked in order of urgency with the most urgent jobs placed at the
top. Queue: Jobs can be queued in order of urgency with the most urgent jobs joining the queue first.
Question 4
if(a[mid1] == x)
return mid1;
if(a[mid2] == x)
return mid2;
if(x < a[mid1])
last = mid1 - 1;
else if(x > a[mid1] && x < a[mid2])
{
first = mid1 + 1;
last = mid2 - 1;
}
else // this means x > a[mid2]
first = mid2 + 1;
Downloaded
by:by:
NkuliMckintosh
| vicdp94@gmail.com
Downloaded
Junerdiki | Junerdiki@gmsil.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 5
5.1
Selection sort
4
7
10
23
18
43
43
19
5
66
14
4
5
10
23
18
43
43
19
7
66
14
4
5
7
23
18
43
43
19
10
66
14
4
5
7
10
18
43
43
19
23
66
14
5.2.
Downloaded
by:by:
NkuliMckintosh
| vicdp94@gmail.com
Downloaded
Junerdiki | Junerdiki@gmsil.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 6
template<class Type>
void bSearchTreeType<Type>::printInRange(binaryTreeNode<Type> node,
int low, int high)
{
if(node == NULL)
return;
if(node->info >= low && node->info <= high)
cout << node->info << " " << endl;
printInRange(node->llink, low, high);
printInRange(node->rlink, low, high);
}
Question 7
A
B
C
D
E
F
smallestWeight
0
-
1
-
-
-
weightFound
T
F
F
F
F
F
smallestWeight
0
-
1
3
5
-
weightFound
T
F
T
F
F
F
smallestWeight
0
-
1
3
5
8
weightFound
T
F
T
T
F
F
smallestWeight
0
-
1
3
5
6
weightFound
T
F
T
T
T
F
smallestWeight
0
-
1
3
5
6
weightFound
T
F
T
T
T
T
smallestWeight
0
-
1
3
5
6
weightFound
T
T
T
T
T
T
By edmund@vtutorOnline.com
All the best.
Downloaded
by:by:
NkuliMckintosh
| vicdp94@gmail.com
Downloaded
Junerdiki | Junerdiki@gmsil.com
Distribution of this document is illegal
Powered by TCPDF (www.tcpdf.org)
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
COS2611 June 2018 (pII)
Question 1
1C
2A
3D
4D
5A
6D
7C
8C
9D
10A
Question 2
template<class Type>
void linkedListType<Type>::divideAt(linkedListType<Type> &subList, int
pos)
{
nodeType<Type> *current = first;
for(int i = 1; i < pos; i++)
{
current = current->link;
}
subList->last = last;
last = current;
subList->first = current->link;
current->link = NULL;
subList->count = count - pos;
count = pos;
}
Question 3
3.1
34521
3.2
Requeues items in a queue in reverse order.
3.3.
n must be greater or equal to 1 and queue must have at least one item.
Downloaded
by:by:
NkuliMckintosh
| vicdp94@gmail.com
Downloaded
Junerdiki | Junerdiki@gmsil.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 4
template<class Type>
void reverseS(stackADT<Type> &s)
{
queueADT<Type> q;
q.initializeQueue();
while(!s.inEmptyStack())
{
q.addQueue(s.top());
s.pop();
}
while(!q.isEmptyQueue())
{
s.push(q.front());
q.deleteQueue();
}
}
Question 5
0
1
2
3
4
5
6
7
8
9
10
sList[first]
sList[mid]
sList[last]
0
5
10
6
8
10
9
9
10
10
10
10
Question 6
6.1
10
18
10
15
21
21
28
28
25
25
30
30
12
12
71
71
32
32
Downloaded
by:by:
NkuliMckintosh
| vicdp94@gmail.com
Downloaded
Junerdiki | Junerdiki@gmsil.com
Distribution of this document is illegal
58
58
15
18
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
6.2
15
18
21
10
25
28
12
30
32
58
71
10
18
21
15
25
28
12
30
32
58
71
6.3.
In insertion sort, each item in the unsorted array has to be compared with each of its preceding items
and moving it to the left if its greater.
6.4
Merge sort partitions the list in the middle while quick sort uses a pivot and partitions the list by moving
all items less than the pivot to the left and those greater to the right.
Question 7
7.1
Downloaded
by:by:
NkuliMckintosh
| vicdp94@gmail.com
Downloaded
Junerdiki | Junerdiki@gmsil.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
7.2
template<class elemType>
elemType bSearchTreeType<elemType>::max()
{
binaryTreeNode<elemType> *current = root;
binaryTreeNode<elemType> *max;
while(current != NULL)
{
max = current;
current = current->rlink;
}
return max->info;
}
Downloaded
by:by:
NkuliMckintosh
| vicdp94@gmail.com
Downloaded
Junerdiki | Junerdiki@gmsil.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 8
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
0
0
T
0
T
0
T
1
2
F
2
T
2
T
2
F
F
11
F
3
12
F
3
F
3
T
4
F
12
F
6
F
5
F
F
7
F
6
F
F
7
F
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
0
T
0
T
0
T
0
T
0
T
2
T
2
T
2
T
2
T
2
T
11
F
11
F
11
F
11
F
11
T
3
T
3
T
3
T
3
T
3
T
6
F
6
T
6
T
6
T
6
T
7
F
7
F
7
T
7
T
7
T
7
F
7
F
7
F
7
T
7
T
By edmund@vtutorOnline.com
All the best 😊
Downloaded
by:by:
NkuliMckintosh
| vicdp94@gmail.com
Downloaded
Junerdiki | Junerdiki@gmsil.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
2018 June Examination Memo:
Question 1:
1.1 - A
1.6 - C
1.2 - E
1.7 - D
1.3 - E
1.8 - B
1.4 - A
1.9 - C
1.5 - B
1.10 - D
Question 2:
template <class Type>
void unorderedLinkedList<Type>::deleteSmallest()
{
nodeType<Type> *current;
nodeType<Type> *trailCurrent;
nodeType<Type> *small;
nodeType<Type> *trailSmall;
if (first == NULL)
cout << "Cannot delete from an empty list." << endl;
else
if (first->link == NULL)
{
first = NULL;
delete last;
last = NULL;
}
else
{
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
small = first;
trailCurrent = first;
current = first->link;
while (current != NULL)
{
if (small->info > current->info)
{
trailSmall = trailCurrent;
small = current;
trailCurrent = current;
current = current->link;
}
if (small == first)
first = first->link;
else
{
trailSmall->link = small->link;
if (small == last)
last = trailSmall;
}
delete small;
}
}
Question 3:
Iteration sArray [first] sArray [mid] sArray [last]
1
10
41
100
2
45
68
100
3
70
90
100
4
100
100
100
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 4:
template <class Type>
void oddQ (queueType<Type> &q)
{
queueType<Type> temp;
while(!q.isEmptyQueue())
{
temp.addQueue(q.front());
q.deleteQueue();
if(!q.isEmptyQueue())
q.deleteQueue();
}
while (!temp.isEmptyQueue())
{
q.addQueue(temp.front());
temp.deleteQueue();
}
}
Question 5:
bool isInLanguageL (string w)
{
stackType<char> s;
int index =0;
//read the of a's
while(w[index]=='a')
{
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
s.push('X'); //****alternatively we can push 2 X’s for every a
index++;
}
//read the b's and pop the stack twice
while(w[index]=='b')
//****then we can pop an X for every b
{
if(!s.isEmptyStack()){
s.pop();
if(!s.isEmptyStack())
s.pop();
else
return false;
}
else
return false;
index++;
}
return (index == w.size()&& s.isEmptyStack());
}
Question 6:
1
7
9
2
3
Iteration 1 3
7
1
2
9
Iteration 2 2
3
1
7
9
Iteration 3 1
2
3
7
9
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 7:
template <class Type>
int binaryTreeType<Type>::nodeCount(binaryTreeNode<Type> *p) const
{
if (p == NULL)
return 0;
else
return 1 + nodeCount(p->llink) + nodeCount(p->rlink);
}
Question 8:
0
1
2
3
4
SmallestWeight 0
6
∞
3
2
WeightFound
T
F
F
F
F
SmallestWeight 0
4
∞
3
2
WeightFound
T
F
F
F
T
SmallestWeight 0
4
5
3
2
WeightFound
T
F
F
T
T
SmallestWeight 0
4
5
3
2
WeightFound
T
T
F
T
T
SmallestWeight 0
4
5
3
2
WeightFound
T
T
T
T
T
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
OCT/NOV 20117
Question 1
1.1 C
1.2 B
1.3 A
1.4 D
1.5 A
1.6 D
1.7 C
1.8 C
1.9 D
1.10 D
Question 2
template<class Type>
void linkedListType<type>::divideAt(linkedListType<Type> & subList, int pos)
{
nodeType<Type> *current;
nodeType<Type> *prev;
int i;
if(pos < count)
{
prev = first;
current = first->link;
for ( i = 2; i<= pos; i++)
{
prev = prev->link;
current = current->link;
}
subList.first = current;
subList.last = last;
last = prev;
last->link = NULL;
sublist.count = count-i;
count = length-pos;
}
}
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 3
Iteration
First
Last
Mid
1
2
100
41
2
2
40
16
Question 4
template <class Type>
bool identicalQ (queueType <Type> Q1, queueType <Type> Q2)
{
while ((!Q1.isEmptyQueue())&& (!Q2.isEmptyQueue()))
{
if(Q1.front()!= Q2.front())
return false;
Q1.deleteQueue();
Q2.deleteQueue();
}
if(Q1.isEmptyQueue()&& Q2.isEmptyQueue())
return true;
return false;
Question 5
//a^nb^(n-1)
bool isInLanguageL (string w)
{
stackType<char> s;
int index =0;
//read the extra a and go to the next character in the
string w
if(w[index]=='a')
index++;
//read the rest of a's
while(w[index]=='a')
{
s.push('X');
index++;
}
//read the remaining b's
while(w[index]=='b')
{
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
if(!s.isEmptyStack()){
if(s.top()=='X'
s.pop();
}
else
return false;
index++;
}
return (index == w.size()&& s.isEmptyStack());
}
Question 6
To be uploaded tomorrow
Question 7
Preorder:
–*x+yz/–abc
Inorder:
x*y+z–a–b/c
Postorder:
xyz+*ab–c/–
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
COS2611: June 2017 Paper I Answers
www.vtutoronline.com
Question 1
1: B
2: B
3: B
4: E
5: B
6: B
7: D
8: C
9: C
10: C
Question 2
template <class Type>
deleteOc (orderedLinkedList<Type> L1, const ... L2)
{
nodeType<Type> *current = L2.first;
while(current != NULL)
{
if(L1.search(current->info)
{
L1.deleteNode(current->info);
L1.count--;
}
}
}
Question 3
template <class Type>
int recSeqSearch(const vector<int> &a, const Type &x, int i, int last)
{
if(i > last)
return -1;
if(a[i] == x)
return i;
recSeqSearch(a, x, i + 1, last);
}
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 4
template <class Type>
void reverseEverySecondItem(queueType<Type> &q)
{
queueType<Type> tempQ;
tempQ.initializeQueue();
stackType<Type> tempS;
tempS.initializeStack();
while(!q.isEmptyQueue())
{
tempQ.addQueue(q.front());
q.deleteQueue();
if(!q.isEmptyQueue())
{
tempS.push(q.front());
q.deleteQueue();
}
}
while(!tempQ.isEmptyQueue())
{
q.addQueue(tempQ.front())
tempQ.deleteQueue();
if(!tempS.isEmptyStack())
{
q.addQueue(tempS.top());
tempS.pop();
}
}
}
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 5
bool isInLanguage(string w)
{
stackType<char> tempS;
tempS.initializeStack();
int i = w.size() – 1;
while(i >= 0 && w[i] == 'b’)
{
tempS.push('x');
i--;
}
while(i >= 0 && w[i] == 'a')
{
if(tempS.isEmptyStack())
{
return false;
}
tempS.pop();
i--;
}
if(tempS.isEmptyStack())
{
return false;
}
tempS.pop();
return i < 0 && tempS.isEmptyStack();
}
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 6
Question 7
Question 8
sw
wf
sw
wf
sw
wf
sw
wf
sw
wf
sw
wf
[0]
0
T
0
T
0
T
0
T
0
T
[1]
2
F
2
T
2
T
2
T
2
T
[2]
4
F
3
F
3
T
3
T
3
T
[3]
8
F
8
F
6
F
6
T
6
T
[4]
F
F
F
9
F
9
T
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
June 2016
Question 2
template <class Type>
void divideMid(linkedListType<Type> &subList)
{
if(count < 2)
return;
int mid = count / 2;
nodeType<Type> current = first;
for(int i = 1; i <= mid + (count % 2); i++)
{
current = current->link;
}
subList.last = last;
last = current;
subList.first = last->link;
last->link = NULL;
sublist.count = mid;
count = count - mid;
}
Question 3
Same as June 2017
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 4
template <class Type>
void removeMin(queueType<Type> &q)
{
queueType<Type> tempQ;
tempQ.initializeQueue();
Type smallest = q.front();
tempQ.addQueue(q.front());
q.deleteQueue();
while(!q.isEmptyQueue())
{
if(q.front() < smallest)
smallest = q.front();
tempQ.addQueue(q.front());
q.deleteQueue();
}
while(!tempQ.isEmptyQueue())
{
if(smallest != tempQ.front())
{
q.addQueue(tempQ.front());
}
tempQ.deleteQueue();
}
}
Question 5
Same as June 2017
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 6
Selection sort
2
5
7
4
12
8
2
5
7
4
12
8
2
4
7
5
12
8
2
4
5
7
12
8
2
4
5
7
12
8
2
4
5
7
8
12
2
4
5
7
8
12
Quick sort
4
5
2
7
12
8
2
4
5
7
12
8
2
4
5
7
12
8
2
4
5
7
12
8
2
4
5
7
8
12
2
4
5
7
8
12
Question 7
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 7.2
Question 8
0
1
2
3
4
5
sw
0
1
-
7
-
-
wf
T
F
F
F
F
F
sw
0
1
3
7
-
4
wf
T
T
F
F
F
F
sw
0
1
3
7
5
4
wf
T
T
T
F
F
F
sw
0
1
3
7
5
4
wf
T
T
T
F
F
T
sw
0
1
3
7
5
4
wf
T
T
T
F
T
T
sw
0
1
3
7
5
4
wf
T
T
T
T
T
T
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
May / June 2015
Question 1:
1.1. D
1.2. C
1.3. A
1.4. E
1.5. E
1.6. D
1.7. B
1.8. D
1.9. C
1.10. D
Question 2:
template <class Type>
void linkedListType<Type>::deleteKthElement (int k)
{
nodeType<Type> *current = first;
nodeType<Type> *prevCurrent = NULL;
if (current == NULL)
return;
else
if (current != NULL)
{
if(k == 1)
{
prevCurrent = first;
first = current->link;
delete prevCurrent;
count--;
return;
}
else
for (int i = 1; i < k; i++)
{
prevCurrent = current;
current = current->link;
}
prevCurrent->link = current->link;
current = prevCurrent;
delete prevCurrent;
count--;
}
};
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 3:
[0] = 1
[0] = 1
[0] = 1
[7] = 8
[3] = 4
[1] = 2
[14] = 15
[6] = 7
[2] = 3
Question 4:
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 5:
bool isInLanguageL(string w)
{
stackType<char> s;
s.initializeStack();
if(w == “”)
return false;
else
{
while (w[index] == 'a')
{
s.push('X');
s.push('X');
index++;
}
while (w[index] == 'b')
{
if(s.top() == ‘X’)
{
s.pop();
index ++;
}
}
}
return (s.isEmptyStack && index = w.size());
}
Question 6:
6.1)
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
6.2)
Question 7:
7.1
4
5
1
6
2
3
7.2
S
T
O
L
B
N
A
D
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 8:
0
1
2
3
4
5
SW
WF
SW
WF
SW
WF
SW
WF
SW
WF
SW
WF
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
COS2611 OCT/NOV MEMO 2014
Question 1 [20]
1. A
2. B
3. C
4. C
5. A
6. C
7. D
8. B
9. B
10. D
Question 2 [10]
template <class Type>
void linkedListType<Type>::removeMin()
{
nodeType<Typ> *current = first ->link;
nodeType<Typ> *prevCurrent = first;
nodeType<Typ> *smallest = first;
nodeType<Typ> *trailSmallest = first;
while(current != NULL)
{
if(current -> info < smallest -> info)
{
smallest = current;
trailSmallest = trailCurrent;
}
current = current -> link;
trailCurrent = trailCurrent -> link;
}
if(first = smallest)
first = first ->link;
else
prevSmalest->link = smallest->link;
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
if(last = smallest)
last = trailSmallest;
count--;
delete smallest;
}
Question 3 [4]
sArray[First] aArray[Mid] sArray[Last]
4
39
95
4
19
39
4
8
19
Question 4 [7]
template <class Type>
void removeEverySecondItem(queueType<Type> & q)
{
queueType<Type> tempQ;
while(!q.isEmptyQueue())
{
tempQ.addQueue(q.front());
q.deleteQueue();
if(!q.isEmptyQueue())
q.deleteQueue();
}
while(!tempQ.isEmptyQueue())
{
q.addQueue(tempQ.front());
tempQ.deleteQueue();
}
}
Question 5 [9]
bool isInLanguageL (queueType<char> &w)
{
stackType<char> s;
while(!w.isEmptyQueue() && w.front()=='a')
{
s.push('X');
s.push('X');
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
w.deleteQueue();
}
while(!w.isEmptyQueue()&& w.front()=='b' )
{
if(!s.isEmptyStack()){
if(s.top()=='X')
s.pop();
}
else
return false;
w.deleteQueue();
}
return (w.isEmptyQueue() && s.isEmptyStack());
}
Question 6 [6]
a)
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
b)
6
1
1
1
1
3
3
3
3
3
1
6
6
5
5
5
5
5
6
6
Pivot= (3)
(1)
(6)
(5)
Question 7 [6]
Preorder: JCBADEFIGH
Inorder : ABCEDJFGIH
The binary tree looks like this:
J
F
C
B
D
A
I
E
G
H
Question 8 [8]
SW
WF
SW
WF
SW
WF
SW
0
0
T
0
T
0
T
0
1
5
F
5
F
5
T
5
2
2
F
2
T
2
T
2
3
∞
F
6
F
6
F
6
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
4
∞
F
∞
F
∞
F
8
5
∞
F
9
F
8
F
8
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
WF
SW
WF
SW
WF
T
0
T
0
T
T
5
T
5
T
T
2
T
2
T
T
6
T
6
T
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
F
8
F
8
T
F
8
T
8
T
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
This paper consists of 9 pages including 2 pages of Appendix (Page 8 and 9).
Instructions
1.
Answer all questions.
2.
All rough work must be done in your answer book.
3.
The mark for each question is given in brackets next to the question.
[Turn over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
2
COS2611
May/June 2014
QUESTION 1 [20]
For each of following questions choose the correct alternative.
1. What is the Big-Oh value for the following function: 1000 + 3n2 + n log n?
A.
B.
C.
D.
E.
O( n)
O( n log n)
O(1000)
O(log n)
O(n2)
2. What is the running time of the following code fragment?
int i;
for (i = 1; i<n; i++)
for (int j = 0; j <i; j++)
cout <<”***”;
cout << endl;
A.
B.
C.
D.
E.
O(log n)
O(n log n)
O(n2)
O(n)
O(1)
3. What is the running time of the following code fragment?
int i;
for(i=1; i<n; i++);
for (int j = 0; j <i; j++)
cout <<”***”;
cout << endl;
A.
B.
C.
D.
E.
O(log n)
O(n log n)
O(n2)
O(n)
O(n2 log n)
4. An algorithm takes 5 seconds for an input of size 100. If the algorithm is linear O(n), what is the largest
size of input that can be executed in 25 seconds?
A.
B.
C.
D.
E.
100
500
250
25
None of the above
[Turn over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
3
COS2611
May/June 2014
5. Consider the following list where each node is of type nodeType(see appendix A).
list
18
32
23
43
87
25
45
q
p
What is the output of the following c++ code?
while (q!=NULL){
cout << p->info << “
p = p->link;
q = q -> link->link;
“;
}
A.
B.
C.
D.
E.
18, 32, 23, 43, 87, 25, 45
32, 43, 25
32, 23, 43, 87, 25, 45
32, 23, 43
None of the above
6. A linked list is not a random access data structure such as a(n) ____.
A.
B.
C.
D.
E.
Stack
Pointer
Queue
Array
None of the above
Consider the tree below and answer question 7, 8 and 9.
A
B
C
D
E
7. Which of the following traversals yields ABCDE?
A.
B.
C.
D.
E.
Inorder
Level order
Postorder
Preorder
None of the above
[Turn over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
4
COS2611
May/June 2014
8. Which of the following is an inorder traversal of the tree?
A.
B.
C.
D.
E.
ABCDE
ABDCE
BDECA
EDCBA
BADCE
9. The height of the tree is
A.
B.
C.
D.
E.
0
1
2
3
None of the above
10. Which one of the following statements about Quicksort and Mergesort is not true?
A. Both Quicksort and Mergesort sort a list by partitioning the list.
B. In a Quicksort, the sorting work is done during the partitioning of the list.
C. In a Mergesort, the sorting work is done during the merging of the list.
D. To partition a list, Mergesort selects an item from the list called the pivot.
QUESTION 2[10]
Implement the operation divideAt which is part of class linkedListType (See appendix A). This
operation divides a given list into two sublists.
Consider the following statements:
unorderedLinkedList<int> myList;
unorderedLinkedList<int> subList;
Suppose myList points to the list with elements 34 65 27 89 12 (in this order). The statement:
myList.divideAt(subList, 2);
divides myList into two sublists: myList contains the elements 34 65, and subList contains the
elements 27 89 12.
Use the following header:
void divideAt(linkedListType<Type> &subList, int pos);
You can assume that the list has more than 1 element and that pos >= 1.
[Turn over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
5
COS2611
May/June 2014
QUESTION 3 [4]
Consider the sorted array sArray of integers below.
4
8
19
25
34
39
45
48
66
75
89
95
The Binary Search algorithm uses two index variables first and last to determine the position (stored in
another index variable mid) to search for an element. Using binarySearch to search for the element 89 in
sArray, give the values of sArray[first], sArray[mid] and sArray[last] (in the form of a
table) every time a new value is calculated for mid.
QUESTION 4 [7]
Write a function reverseEvenQ that uses a local stack to reverse elements at even positions a queue.
Suppose the queue has the following elements: A B C D E F G, where A is the front of the queue. After the call
of reverseEvenQ, the contents of the queue are now: A F C D E B G.
Use the following header:
template <class Type>
void reverseEvenQ (queueType<Type> & q)
You can make use of any member functions of class stackType and class queueType (See appendix
B and C). Note that this function is not a member of the class stackType.
QUESTION 5 [8]
L={anbn} where n ≥1, is a language of all words with the following properties:
•
•
•
The words are made up of strings of a’s followed by b’s.
The number of a’s is always equal to the number of b’s.
Examples of words that belong to L are
ab, where n=1;
aabb, where n=2;
aaabbb, where n=3;
aaaabbbb, where n=4.
One way to test if a word w belong to this language is to use a stack to check if the number of a’s balances the
number of b’s. Use the provided header and write a function isInLanguageL that uses a stack to test if any
word belongs to L.
bool isInLanguageL (string w);
[Turn over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
6
COS2611
May/June 2014
QUESTION 6 [6]
Consider the following sequence of numbers: 3, 4, 2, 1
a) Sort the list using Merge sort. The resulting sub-arrays at each phase should be drawn in a tree-like
fashion.
(2)
b) Sort the list using Quick sort with the middle element as pivot. Show the state of the list after each call
to the partition procedure. Indicate the pivots in each list.
(4)
QUESTION 7 [6]
Write a recursive function treeHeight that calculates the height of a binary search tree. The height of a
binary search tree is the maximum level in the tree. Use the following driver function and header:
Driver function:
template<class Type>
int bSearchTreeType<Type>::treeHeight( )
{
if (root != NULL)
return treeHeight( root );
return -1;
}
Header:
template<class Type>
int bSearchTreeType<Type>::treeHeight(bSearchTreeType<Type> *p);
[Turn over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
7
COS2611
May/June 2014
QUESTION 8 [10]
Consider the graph below and answer the following questions:
a) Draw the adjacency list of the graph.
(2)
b) Use the shortest path algorithm to find the shortest distance from node 0 to every other node of the
graph. Give only the contents of the arrays smallestWeight and weightFound for each
iteration of the algorithm. Do not redraw the diagram.
(7)
[Turn over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
8
COS2611
May/June 2014
Appendix A
template <class Type>
struct nodeType
{
Type info;
nodeType<Type> *link;
};
template <class Type>
class linkedListType
{
public:
const linkedListType<Type>& operator=
(const linkedListType<Type>&);
void initializeList();
bool isEmptyList() const;
void print() const;
int length() const;
void destroyList();
Type front() const;
Type back() const;
bool search(const Type& searchItem);
void insertFirst(const Type& newItem);
void insertLast(const Type& newItem);
void deleteNode(const Type& deleteItem);
linkedListIterator<Type> begin();
linkedListIterator<Type> end();
linkedListType();
linkedListType(const linkedListType<Type>& otherList);
~linkedListType();
protected:
int count;
nodeType<Type> *first;
nodeType<Type> *last;
private:
void copyList(const linkedListType<Type>& otherList);
};
template <class Type>
class unorderedLinkedList: public linkedListType<Type>
{
public:
bool search(const Type& searchItem) const;
void insertFirst(const Type& newItem);
void insertLast(const Type& newItem);
void deleteNode(const Type& deleteItem);
};
[Turn over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
9
COS2611
May/June 2014
Appendix B
template <class Type>
class stackType
{
public:
void initializeStack();
bool isEmptyStack() const;
bool isFullStack() const;
void push(const Type& newItem);
Type top() const;
void pop();
};
Appendix C
template <class Type>
class queueType
{
friend void moveNthFront (queueType<Type> & q, int n);
public:
bool isEmptyQueue() const;
bool isFullQueue() const;
void initializeQueue();
Type front() const;
Type back() const;
void addQueue(const Type& queueElement);
void deleteQueue();
private:
int count;
};
Appendix D
template <class Type>
class bSearchTreeType: public binaryTreeType<Type>
{
public:
bool search(const Type& searchItem) const;
void insert(const Type& insertItem);
void deleteNode(const Type & deleteItem);
private:
void deleteFromTree(binaryTreeNode<Type>* &p);
};
©
UNISA 2014
[Turn over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Cos2611 May/June Memo 2014
Question 1 (20)
1. E
2. C
3. D
4. B
5. D
6. D
7. D
8. E
9. D
10. D
Question 2 (10)
template<class Type>
void linkedListType<type>::divideAt(linkedListType<Type> &
subList, int pos)
{
nodeType<Type> *current;
nodeType<Type> *prev;
int i;
if(pos < count)
{
prev = first;
current = firs->link;
for ( i = 2; i<= pos; i++)
{
prev = prev->link;
current = current->link;
}
subList.first = current->link;
subList.last = last;
last = prev;
last->link = NULL;
sublist.count = count-i;
count = length-pos;
}
}
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 3 (4)
Iteration
1
2
3
First √√
4
45
75
Last
95
95
95
Mid √√
39
66
89
Question 4 (7)
void reverseEvenQ (queueType<Type> & q)
{
stackType<Type> tempS;
queueType<Type> tempQ;
while(!q.isEmptyQueue())
{
tempQ.addQueue(q.front());
q.deleteQueue();
if(!q.isEmptyQueue())
{
tempS.push(q.front());
q.deleteQueue();
}
}
while(!tempQ.isEmptyQueue() && !tempS.isEmptyStack())
{
q.addQueue(tempQ.front());
q.addQueue(tempS.top());
tempQ.deleteQueue();
tempS.pop();
}
}
Question 5 (8)
bool isInLanguageL2 (string w)
{
stackType<char> s;
int index =0;
while(w[index]=='a')
{
s.push('X');
s.push('X');
index++;
}
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
while(w[index]=='b')
{
if(!s.isEmptyStack()){
if(s.top()=='X')
s.pop();
}
else
return false;
index++;
}
return (index == w.length()&& s.isEmptyStack());
}
Question 6 (6)
a)
3421
34
3
21
4
34
1
2
12
1234
b)
3421
4
1324
3
2134
2
1234
1
1234
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 7 (6)
template<class Type>
int bSearchTreeType<Type>::treeHeight(bSearchTree<Type> *p)
{
if (p == NULL)
return 0;
else
{
int leftHeight = treeHeight(p->llink);
int rightHeight = treeHeight(p->rlink);
if (leftHeight > rightHeight)
return 1 + leftHeight;
else
return 1 + rightHeight;
}
}
Question 8 (9)
a)
0:1->2
1:3
2:3->4
3:4
4:
5: 0->4
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
b)
SmallW
WeighF
SmallW
WeighF
SmallW
WeighF
SmallW
WeighF
SmallW
WeighF
SmallW
WeighF
[0]
0
T
0
T
0
T
0
T
0
T
0
T
[1]
5
F
5
F
5
T
5
T
5
T
5
T
[2]
2
F
2
T
2
T
2
T
2
T
2
T
[3]
∞
F
3
F
3
F
3
T
3
T
3
T
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
[4]
∞
F
11
F
11
F
5
F
5
T
5
T
[5]
∞
F
∞
F
∞
F
∞
F
∞
F
∞
F
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
COS2611 Oct/Nov 2013 Memo
Question 1 [20]
1. B √√
2. B √√
3. D √√
4. D √√
5. C √√
6. C √√
7. B √√
8. B √√
9. B √√
10. D √√
Question 2 [10]
template<class Type>
void linkedListType<type>::divideAt(linkedListType<Type> &
subList, int pos)
{
nodeType<Type> *current;√
nodeType<Type> *prev;
int i;
if(pos < count) √
{
prev = first;
current = firs->link; √
for ( i = 2; i<= pos; i++)√
{
prev = prev->link; √
current = current->link; √
}
subList.first = current->link; √
subList.last = last; √
last = prev; √
last->link = NULL;
sublist.count = count-i; √
count = length-pos;
}
}
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Question 3[4]
1. a. false; b. true; c. true; d. true √√
2. a. 8; b. 6 √√
Question 4 [6]
template < class Type >
void replaceItem( stackType< Type > & s, const Type & oldItem, const
Type & newItem)
{
stackType<Type> tempS; √
while(!s.isEmptyStack())
{
if(s.top()==oldItem) √
tempS.push(newItem); √
else
tempS.push(s.top());√
s.pop();
}
while(!tempS.isEmptyStack())√
{
s.push(tempS.top());√
tempS.pop();
}
}
Question 5 [7]
template <class Type>
void removeEverySecondItem(queueType<Type> & q)
{
queueType<Type> tempQ; √
while(!q.isEmptyQueue())√
{
tempQ.addQueue(q.front());√
q.deleteQueue();
if(!q.isEmptyQueue())√
q.deleteQueue();√
}
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
while(!tempQ.isEmptyQueue())
{
q.addQueue(tempQ.front());√
tempQ.deleteQueue();√
}
}
Question 6 [8]
√√√
[0]
[1]
[2]
[3]
[4]
[5]
[6]
6
3
5
7
4
2
1
3
6
5
7
4
2
1
3
5
6
7
4
2
1
3
5
6
7
4
2
1
3
4
5
6
7
2
1
2
3
4
5
6
7
1
1
2
3
4
5
6
7
[0]
[1]
[2]
[3]
[4]
[5]
[6]
1
3
5
6
4
2
7
√
2
3
1
4
5
6
7
√√
1
3
2
4
5
6
7
√√
Question 7 [7]
a)
i.
50 30 25 40 80 98 √
ii.
25 40 30 98 80 50 √
iii.
25 30 40 50 80 98 √
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
b)
Template<class Type>
nodeType<Type> *findMin( nodeType<Type> * t)
{
If( t != NULL) √
while( t->left != NULL) √
t = t->left; √
return t; √
}
Question 8 [8]
SmallW
WeighF
SmallW
WeighF
SmallW
WeighF
SmallW
WeighF
SmallW
WeighF
[0]
0
T
0
T
0
T
0
T
0
T
[1]
2
F
2
T
2
T
2
T
2
T
[2]
21
F
3
F
3
T
3
T
3
T
[3]
∞
F
12
F
6
F
6
T
6
T
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
[4]
∞
F
∞
F
11
F
10
F
10
T
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
COS2611 MEMO MAY/JUNE 2013
QUESTION 1 [20]
For each of following questions choose the correct alternative.
1. A 30 42 20 28===
2. C 24; n log n; n+n3; 2n ====
3. C O(n2)====
4. D O(n)====
5. A 5s===
6. B The search on a linked list is random.====
7. B An array is a Last In Last Out data structure. ====
8. D To partition a list, mergesort selects an item from the list called the pivot.
9. C3 ===
10. D 4 ===
QUESTION 2[10]
template<class Type>
void linkedListType<type>::divideAt(linkedListType<Type> & subList,
int pos)
{
nodeType<Type> *current;
nodeType<Type> *prev;
int i;
if(pos < count)
{
prev = first;
current = firs->link;
for ( i = 2; i<= pos; i++)
{
prev = prev->link;
current = current->link;
}
subList.first = current->link;
subList.last = last;
last = prev;
last->link = NULL;
sublist.count = count-i;
count = length-pos;
}
}
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
2
COS2611
May/June 2013
QUESTION 3 [4]
Iteration
1
2
3
QUESTION 4 [6]
First
[0] = 4
[6]= 45
[9]= 75
Last
[11] =95
[11] =95
[11] =95
Mid
[5]= 39
[8]= 66
[10]= 89
template <class Type>
bool identicalS (stackType<Type> S1, stackType< Type > S2){
if(S1.isEmptyStack() && S2.isEmptyStack())
return true;
else if (S1.isEmptyStack() || S2.isEmptyStack())
return false;
else if (S1.top() != S2.top())
return false;
else{
S1.pop();
S2.pop();
return identicalS(S1, S2);
}
}
QUESTION 5 [8]
template <class Type>
void moveNthFront(queueType<Type> & q, int n)
{
queueType<Type> tempQ, otherQ;
assert (n<=count && n>0)
while(!q.isEmptyQueue())
{
if(n==1)
tempQ.addQueue(q.front());
else
otherQ.addQueue(q.front());
q.deleteQueue();
if(n>=1)
n--;
}
q.addQueue(tempQ.front());
while(!otherQ.isEmptyQueue())
{
q.addQueue(otherQ.front());
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
3
COS2611
May/June 2013
otherQ.isEmptyQueue();
}
}
QUESTION 6 [6]
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
4
COS2611
May/June 2013
QUESTION 7 [8]
a) Preorder: STBAD , inorder: ADBTS
b) Treposition (1mark), Position of O (1), N(1) and L(1)
(1)
(4)
c)
(3)
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
5
COS2611
May/June 2013
QUESTION 8 [8]
It 1
It2
It3
It4
It5
It6
A
B
C
D
E
F
3
0
5
∞
∞
∞
F
T
F
F
F
F
3
0
4
∞
∞
∞
T
T
F
F
F
F
3
0
4
6
8
∞
T
T
T
F
F
F
3
0
4
6
8
11
T
T
T
T
F
F
3
0
4
6
8
9
T
T
T
T
T
F
3
0
4
6
8
9
T
T
T
T
T
T
©
UNISA 2013
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Exam 2012-10
Question 1
1
B
2
C
3
C
4
C
5
C
6
C
7
A
8
A
9
C
10
C
Question 2
template<class Type>
void linkedListType<Type>::deleteKthElement(int k)
{
assert(k <= count);
nodeType<Type> *current;
nodeType<Type> *trailCurrent;
int i;
if(first == NULL)
cout<<"Cannot delete from an empty list."<<endl;
else
if(k == 1)
{
current = first;
first = first->link;
if (first == NULL)
last = NULL;
delete current;
}
else
{
//find the location before kth element
trailCurrent = first;
current = first->link;
for (i = 2;i < k; i++)
{
trailCurrent = current;
current = current->link;
}
trailCurrent->link = current->link;
if(current == last)
last = trailCurrent;
}
}
Question 3
template<class Type>
int sequentialSearch(const vector<type> & a, const Type & x, int low, int
high)
{
if (low > high)
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
return -1;
if (a[low] == x)
return low;
return recSeqSearch(a, x, low+1, high);
}
Question 4
template<class Type>
void reverseFrontN (queueType<Type> & q, int n)
Still working on this question. If anybody can help me with this Q, that will be greatly appreciated.
Question 5
template<class Type>
bool sameStack <stackType<Type> s, stackType<Type> w)
{
if (s.isEmptyStack() && w.isEmptyStack())
return true;
else if (s.isEmptyStack() || w.isEmptyStack())
return false;
else if (s.top() != w.top ())
return false;
else
{
s.pop();
w.pop();
return sameStack (s,w);
}
}
Question 6
1
2
1
3
3
3
5
1
2
6
4
4
4
5
5
2
6
6
7
7
7
Question 7
template<class Type>
int binaryTreeType<Type>::nodeCount(binaryTreeNode<Type> *p)
{
if(p == NULL)
return 0;
else
return 1 + nodeCount(p->llink) + nodeCount(p->rlink);
}
Question 8
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
1
1
2
2
3
3
4
4
5
5
6
6
Index
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
smallestWeight
weightFound
0
0
T
0
T
0
T
0
T
0
T
0
T
1
4
F
4
T
4
T
4
T
4
T
4
T
2
9
F
9
F
9
T
9
T
9
T
9
T
3
F
16
F
12
F
12
T
12
T
12
T
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
4
F
F
F
F
F
29
T
5
F
F
22
F
17
F
17
T
17
T
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
COS2611 Oct/Nov 2011 Memo
QUESTION 1 [8]
1.
2.
3.
4.
C
D
C
D
QUESTION 2 [8]
template<class Type>
void linkedListType<type>::divideAt(linkedListType<Type> & subList, int pos)
{
nodeType<Type> *current;
nodeType<Type> *prev;
int i;
if(pos < count)
{
prev = first;
current = firs->link;
for ( i = 2; i<= pos; i++)
{
prev = prev->link;
current = current->link;
}
subList.first = current->link;
subList.last = last;
last = prev;
last->link = NULL;
sublist.count = count-i;
count = length-pos;
}
}
QUESTION 3 [6]
template <class Type>
int recSeqSearch(const vector<type> & a, const Type &x, int low, int high)
{
if(low>high)
return -1;
if(a[low] == x)
return low;
return recSeqSearch(a, x, low+1, high);
}
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
2
COS2611
Oct/Nov 2011
QUESTION 4 [12]
a)
i.
ii.
iii.
iv.
Queue, this represents a FIFO situation.
Neither, the order of retrieval is neither FIFO or LIFO
Stack, represents a LIFO situation.
Neither, a priority queue is ideal.
b)
template <class Type>
void topN (stackADT<Type> & s, int n)
{
queueADT<Type> q;
while(!s.isEmptyStack()&& n>=0)
{
q.addQueue(s.top());
s.pop();
n--;
}
while(!q.isEmptyQueue())
{
s.push(q.front());
q.deleteQueue();
}
}
QUESTION 5 [8]
template <class Type>
bool identicalQ (queueADT<Type> Q1, queueADT<Type> Q2)
{
while ((!Q1.isEmptyQueue())&& (!Q2.isEmptyQueue()))
{
if(Q1.front()!= Q2.front())
return false;
Q1.deleteQueue();
Q2.deleteQueue();
}
if(Q1.isEmptyQueue()&& Q2.isEmptyQueue())
return true;
return false;
}
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
3
COS2611
Oct/Nov 2011
QUESTION 6[10]
a)
[0]
[1]
[2]
[3]
[4]
[5]
[6]
6
3
5
7
4
2
1
3
6
5
7
4
2
1
3
5
6
7
4
2
1
3
5
6
7
4
2
1
3
4
5
6
7
2
1
2
3
4
5
6
7
1
1
2
3
4
5
6
7
[0]
[1]
[2]
[3]
[4]
[5]
[6]
1
3
5
6
4
2
7
2
3
1
4
5
6
7
1
3
2
4
5
6
7
b)
QUESTION 7 [8]
a)
50
10
72
26
51
96
b) Preorder: 50, 10, 26, 72, 51, 96
Postorde: 26, 10, 51, 96, 72, 50
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
4
COS2611
Oct/Nov 2011
QUESTION 8 [10]
SmallW
WeighF
SmallW
WeighF
SmallW
WeighF
SmallW
WeighF
SmallW
WeighF
[0]
0
T
0
T
0
T
0
T
0
T
[1]
2
F
2
T
2
T
2
T
2
T
[2]
21
F
3
F
3
T
3
T
3
T
[3]
∞
F
12
F
6
F
6
T
6
T
[4]
∞
F
∞
F
11
F
10
F
10
T
©
UNISA 2011
[Turn Over]
Downloaded by: NkuliMckintosh | vicdp94@gmail.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Detailed
COS2611
Summary
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Big-O-Notation and space and
time complexity
Space complexity is how much memory(space) is required by the algorithm if
processed by the computer
Time complexity refers to the time taken by the algorithm to complete(to solve
the algorithm)
Aim of algorithm analysis is to assess the efficiency of an algorithm.
Efficiency -
How much memory algorithm occupies
How much time it takes for algorithm to complete
An algorithm is said to be optimal if it is - processed faster
- utilises fewer memory resources
Compared to others.
Execution time of algorithms
It is dependent on the computer used, programming language &
programmer’s style. When we analyse algorithms, we should
employ mathematical techniques that analyse algorithms
independent of specific - implementations
- computers
- or data
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
To analyse algorithms we 1st count the number of basic operations in a
particular solution. Then we express the efficiency of algorithms using growth
functions.
An basic operation
Is operation that takes 1 time unit to execute. One time unit is
theoretical time taken by a basic operation to complete.
Examples:
o Assignment operation (e.g. today = “Monday”)
o Arithmetic operation (e.g. salary =
hoursWorked*hourlyRate)
o Comparison operation (e.g. age=20)
A single operation: count = count + 1; This takes on
unit of time to complete.
Example: A simple If statement:
Operation Cost
if(n<0)
compare
absval =-n;
assignment 1
1
else
absval = n;
assignment 1
Total Cost = 1+1 = 2 (because only 1 of the assignment statements will be
executed in the if statement, i.e. only one branch)
Example: A simple loop
Cost
i=1;
1
sum=0;
1
while(i<=n){
n+1
i=i+1;
n
sum=sum+1;
n
}
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
n+1 because when loop is on the last iteration it checks the condition again so
the comparison operation will gets executed another time and then it exits the
loop.
Total cost = 3n+3
Running times in general:
Loops: Running time is the running time of the statements inside that
loop times number of iterations
Nested loops: Running time of a nested loop(inner loop) is the addition
of the running time of the statements inside this loop. Take this and
times it by the product of the iteration of the nested loop and the
iteration of the outer loop.
e.g.
Outer(4 iterations){
Nested(3 iterations){
Statement;
Statement;
}
}
Total cost= nested loop’s statements running time * ( iteration of
nested loop*iteration of outer loop)
= 2 * (3 * 4)
= 24
If/Else: Running time is that of the test instruction(the comparison
operation) plus the larger running time of one of the branches.
Order-of-Magnitude Analysis and Big-O Notation
- We measure an algorithm’s time requirement as a function of
its problem size.
- Problem size depends on the application, e.g. Problem size for
an algorithm that calculates 𝑛𝑡ℎ prime numbers, will be
determined by the value n.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
- Say we have algorithm A and it’s problem size is n then we can
say that Algorithm A requires 5*𝑛2 time units to solve a
problem of size n.
- The most important thing to learn is how quickly an algorithm’s
time grows as a function of the problem size.
- Algorithm A requires a running time that is proportional to 𝑛2
- An Algorithms proportional time requirement is known as
growth rate.
- We compare two algorithms by comparing their growth rates.
If algorithm A requires time proportional to f(n), Algorithm A is
said to be order f(n), and it is denoted as O(f(n)).
The function f(n) is called the algorithm’s growth-rate function.
Since the capital O is used in the notation, this notation is
known as the Big-O notation.
If Algorithm A requires time proportional to 𝑛2 , it is O(𝑛2 )
Video on Big-O:
Big-O notation and Time complexity shows you how your functions grows as
your input grows.
We ask the question how much time does it take to run a function? This question
is hard to answer because it is dependent on computer, language, etc.
e.g.function:
def find_sum(given_array):
total = 0
for each I in given_array:
total +=I;
return total;
Note: The more elements in the array the more time it will take to run the
function.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
A better question to ask is: How does the runtime of this function grow as the
size of the input grows.
To answer this question we use Big O notation and Time Complexity(tools we
use to answer this question)
When we run the find_sum function he tested different array sizes and plotted
it on the graph
On y axis is the time it takes and x axis is number of elements in the array.
This pattern is called linear time complexity.
Thus time complexity is a way of showing how the runtime of a function(or
particular code) increases as the size of the input increases.
Types of time complexity:
Time complexity: linear time
Constant time(time doesn’t increase, horizontal line)
Quadratic time
Now a more mathematical way of expressing these time complexities are Big
O Notation:
-linear time can be expressed as O(n) ,n is the size of the input. In this case
the number of elements in the array. Read as “big O of n”
-Constant time can be expressed as O(1)
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
-Quadratic time can be expressed as O(𝑛2 )
In our example and looking at the straight line graph we can write the
function as:
T = an+b (n is size of input, a and b are two constants)
How to find Big-o function from the given function:
Steps:
1. Find the fastest growing term
2. Take out it’s coefficient
3. Then put that into the brackets after the O
Example: T = an+b
Fastest growing term is an, take out a. Thus O(n)=an+b
Example: T=a𝑛2 +dn+e
Fastest growing term is a𝑛2 , take out a. Thus O(𝑛2 )= 𝑎𝑛2 +dn+e
Another example:
given_arr = [1,4,3, … , 10]
function:
def stupid_func(given_arr):
total=0
return total
Running the function and then getting the average running time yields this
graph:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Express this function as T=c=0.115
Expressing this in Big-O notation: Follow the same two steps:
Fastest term is 0.115(there is only 1 term)
0.115 can be written as 0.115 x 1, thus take away 0.115. Thus we left with 1.
Thus T = c = 0.115 = O(1) This is constant time
Let’s say you wrote 2 functions to solve a problem. 1 function is constant
time and the other is linear. E.g.
O(1)
O(n)
Note: Doesn’t matter how big constant is. When the input gets very large
the linear function will take more time than the constant function
Calculating time complexity without running a program and
getting average time.
Example:
given_arr = [1,4,3, … , 10]
function:
def stupid_func(given_arr):
total=0
-> O(1)
//this is assignment operation(it doesn’t depend on
size of input). Thus this line takes the same amount of time, every time. Thus takes
constant amount of time
return total -> O(1)
//This also takes constant amount of time
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
We consider each line of code. We can add the Big-O expressions to
calculate the total time to run entire function.
T is total time to run the function. Thus T=O(1) + O(1)
= 𝑐1 + 𝑐2 (remember O(1) is a
constant value)
= 𝑐3 (adding 2 constants give you
a constant)
= 𝑐3 x 1 (rewriting it so we can
apply the steps)
= O(1)
In general: O(1)+O(1) = O(1)
Example:
given_arr = [1,4,3, … , 10]
function:
def stupid_func(given_arr):
total=0
-> O(1)
for each i in given_array:
our function T2.
total +=i
-> O(1)
//we are going to leave this out of
-> O(1) //takes O(1) for each time it executes
return total
We are going to each line and see how much time each line takes
Thus our function: 𝑇2 = O(1) + n x O(1) + O(1)
n is number of elements in
array
𝑇2 = 𝑐4 + n x 𝑐5 Remember O(1) is constant and adding
constant plus constant is a constant
= O(n)
Example:
given_2D= [ [1,4,3],
Note: There are 𝑛2 number of elements in this array
[3,1,9],
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
[0,5,2]]
function:
def find_sum_2d(given_2D):
total = 0
-> O(1)
for each row in array_2d:
for each i in row:
total +=i
-> O(1)
//constant amount of time each time,
but have to multiply it by number of elements
return total -> O(1)
Thus our function: 𝑇3 = O(1) + 𝑛2 x O(1) + O(1) n is number of elements in
array
𝑇3 = 𝑐6 + 𝑛2 x 𝑐7 Remember O(1) is constant and adding
constant plus constant is a constant
= O(𝑛2 )
Quadratic Time complexity
Example:
function:
def find_sum_2d(given_2D):
total = 0
-> O(1)
for each row in array_2d:
for each i in row:
total +=i
-> O(1)
//constant amount of time each time,
but have to multiply it by number of elements
for each row in array_2d:
for each i in row:
total +=I
-> O(1)
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
return total -> O(1)
Thus our function: 𝑇4 = O(1) + 2𝑛2 x O(1) 2𝑛2 because there are 2 double
for loops, each one is 𝑛2
𝑇4 = 𝑐8 + 2𝑛2 x 𝑐9
Remember O(1) is constant and
adding constant plus constant is a constant
𝑇4 = 𝑐8 + 𝑛2 x 2𝑐9
Rewriting the term
= O(𝑛2 )
Note: O(2𝑛2 ) = O(𝑛2 ) Quadratic time. We use this one O(𝑛2 ) where it
doesn’t have a coefficient
Example:
for(int i = 3; i < 1000; i++)
sum++;
-> O(1)
-> O(1)
Here we know the given array size. Thus it is just going to be O(1)+ O(1) + O(1) + O(1) ….
And we know that O(1)+ O(1)+… = O(1).
Thus answer is O(1)
Example:
for(int i = 0; i < 5n; i += 2) -> O(1)
sum++;
-> O(1)
Here we have incrimations of 2 and also until 5n. Thus our formulae can look something like
this: 𝑇4 = O(1) + 5𝑛/2 x O(1)
But taking the constants away still results in n. Thus answer is O(n)
Note: that even with increment of more than 1 we are still having constant
incrimination, thus constant times a linear function is still just a linear function
thus the answer is O(n)
Example:
for(int i = 0; i < n*n*n; i++) -> O(1)
for(int j = 2; j < n; j++) -> O(1)
sum++;
-> O(1)
So here: Number of times that that code inside a nested loop gets run is times
of the nested loop multiplies times that the outer loop runs , thus the 3rd line
runs: 𝑛3 x 𝑛
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
times. Thus our biggest term will be 𝑘 ∗ 𝑛4 (with k being a constant). Thus the
answer is O(𝑛4 )
Example:
for(int i = 1; i < n; i*=2)
-> O(log n)
for(int j = 0; j < n; j++) -> O(1)
sum++;
-> O(1)
Amount of time each line takes:
i *= 2 The sequence is 2𝑘 , with k being the number of iterations the
1st for loop go through. Now put value of i equal to this:
1st line: O(log n)
i = 2𝑘 , now apply log rule: 𝑙𝑜𝑔2 𝑖 = 𝑘
You can replace i with n, because i will get close to n, it’s dependent on n.
𝑙𝑜𝑔2 𝑛 = 𝑘
This is logarithmic time complexity. It grows logarithmic. k is the growth
representation here. Put it into the Big-O notation:
O(𝑙𝑜𝑔2 𝑛) = O(log 𝑛)
This is true apparently.
For now if the incrimination goes up with multiplication then it’s log
2st line: Because 2nd line if in the 1st for loop it gets incremented the same
amount of time as the top for loop. Thus it has the same time complexity, i.e.
log n, but it also has its own time complexity which is n.
Thus to find the amount of time for a nested loop is nested loop’s running time
times by running time of it’s outer for loop. Thus answer is n x log n
3rd line: Will be the same as the nested for loop. i.e.: n x log n.
Thus fastest growing term is n x log n, and then take big-O of it we get
O(n logn)
Note: O(log n) is very efficient and used in searches like binary search where
50% of the iterations is taken away.
Example:
for(int i = 1; i < n; i*=2)
sum++;
for(int j = 0; j < n*n; j++)
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
sum++;
The 1st for loop will have time complexity of log n
and the 2nd one will have time complexity of 𝑛2
The function can look like this: 𝑇3 = 𝑛2 x O(1) + log n x O(1)
Fastest growing term is 𝑛2 x O(1)
Take constant away and write it in parenthesis: O(𝑛2 )
Example:
An algorithm takes 20 seconds for an input size of 10. How long will it take for an input size
of 100 if the running time is O(log n)?
log 10 = 1 time unit. 1 time unit takes 20 seconds.
log 100 = 2 time units.
Thus 2 x 20 = 40 seconds.
Example:
An algorithm takes 10 seconds for an input size of 4. How long will it take for an input size of
8 if the running time is O(2𝑛 )?
24 = 16. Thus 16 time units occupies 10 seconds. Thus 10/16 = 0.625 seconds per time unit
28 = 256time units
256 𝑡𝑖𝑚𝑒 𝑢𝑛𝑖𝑡𝑠 ∗ 0.625𝑠𝑒𝑐/𝑡𝑖𝑚𝑒𝑈𝑛𝑖𝑡 = 160 𝑠𝑒𝑐𝑜𝑛𝑑𝑠
Example:
An algorithm takes 2 seconds for an input size of 10. How large a problem can be solved in
25 seconds if the running time is O(𝑛2 )?
102 = 100 time units.
Time units per second: 100/2 = 50 time units per second.
In 25 seconds there are 25 x 50 = 1250 time units available.
Thus 𝑛2 = 1250
Thus 𝑛 = √1250
Thus n = 35.4
Example:
Which of the following functions has the fasted growth rate (for n > 1)?
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
1.
2.
n^2
n log n
3.
4.
n^3
log n + 220
Answer: 3
,because cubic function has largest growing rate
Example:
Which of the following functions is ordered by growth rate from largest to smallest?
1.
n log n; 2^n ;
n^3; 2^4
2^n; n^3; n log
n; 2^4
2.
Answer: 2
3.
4.
2^4; n log n;
n^3; 2^n
2^n ; 2^4; n^3; n
log n;
, 2^n is the fastest, you can test.
Example:
i = 1;
while (i<=n){
for (int j=1; j<10; j++)
i++;}
doIt();
where doIt() has runtime of n^2.
Explanation:
i = 1; -> O(1)
,i.e. constant running time, say constant c
The while for loop has time complexity of O(n).
Then the inner for loop is constant time complexity, i.e. O(1), because it will always have
constant running time because it is not dependent on a variable(it will always run 9
times)
The while loop have linear running time, say n
Thus the nested loop is outer loop times nested loop’s iteration. Thus we get O(n) x O(1)
= O(n) x k
(k is constant)
The i++ is nested in the nested(for) loop thus it also have the same running time of the
nested for loop: O(n) x k
(k is constant)
The doIt() function alone has time complexity of O(𝑛2 )
Thus, the function can be expressed as something like this T = c + n + kn + kn + s𝑛2
Applying the steps: O(𝑛2 )
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Stacks
A stack is a data structure which we can use store information/data.
Here is a representation of a stack.
Here we have 5 nodes containing information in them. The nodes are stacked
on top of each other. Notice the nodes are the same nodes as linked lists. The
nodes point to each other. Each node point to the node below it
We have 2 main functions to manipulate the stack:
Push: Add item to the top
Pop: Remove item from the top
Note: We are always changing the stack from the top, i.e. elements are added
and removed from one end only.
Because of these two function we call a stack LIFO- Last in first out.
When we add nodes to the stack the last element will enter the stack last(we
add from top)
When removing nodes the 1st node in our list will be removed 1st.
An example with Pseudo code:
Say we have declared the Stack pointer. In the beginning it point to Null:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Then we call the function Push(1): It will create a 1st node and then give
it the data of 1. Also it will let ‘Stack pointer’ point to the created node
Call Push again: Push(3)
Note our stack pointer moved to the top node(the newly created node)
Push(5):
Calling the pop function: Pop(). Note it doesn’t take an argument:
Note: We keep the 5 node say we want to do something with it, but it is
no longer apart of the stack
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Creating a stack in code:
In main.cpp
#include "Stack.h"
#include <iostream>
using namespace std;
int main()
{
Stack stck;
//create a Stack object
stck.Push("Franco", 3);
name variable
//create a new item(1st item) with Franco in the
//and 3 in the integer variable.
Remember item is a struct
stck.Push("dude", 6);
item
stck.Push("awe", 8);
stck.Push("coffee", 8);
//remember this will get added to the top of 1st
//now this will be on top
//now this one, lol
stck.Print(); //notice if you print it the 1st created item will be at the
bottom
cout << "************ Popping *****************" << endl;
stck.Pop();
//removes top which is coffee
cout << " ************ Popping *****************" << endl;
stck.Pop();
//removes top one which is awe
cout << " Printing the entire stack after the pop functions:" << endl <<
endl ;
stck.Print(); //notice if you print it the 1st created item will be at the
bottom
cout << " Now!! popping 3 times more:" << endl;
stck.Pop();
stck.Pop();
stck.Pop();
coded it in out
//this will output: 'There is nothing in the stack' since we
//pop function if it is called, but the stack is empty
cout << " Buiding new stack:" << endl<< endl;
stck.Push("yo",5);
stck.Push("ma", 7);
stck.Push("bru", 8);
cout << " The new stack:" << endl;
stck.Print();
return 0;
}
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
In Stack.h
#ifndef STACK_H_
#define STACK_H_
#include <iostream>
using namespace std;
class Stack {
private:
//need to define an item-the nodes that is on top of each other
//consist of these items
struct item
{
string name;
int value;
//we want each item to point to the item below it
item* prev; //item pointer that point to the previous item
};
//need to define the stack pointer-it needs to point to top item
item* stackPtr;
public:
Stack();
~Stack();
//the Push function-adding item on stack
void Push(string name,int value);
//function creates a new item, then store name and value in the item
//and then put the item on top of the stack
void Pop();
//It will remove and item of the stack
void ReadItem(item* r);
//display contents of the given item
void Print();
//print content of the stack
};
#endif /* STACK_H_ */
In Stack.cpp
#include "Stack.h"
#include <cstdlib>
Stack::Stack()
{
stackPtr = NULL;
//when you create a new stack object make sure
//stackPtr point to Null
}
Stack::~Stack()
{
//either 2 thing can happen. the stack is empty
//or the stack has items in it
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
//both these pointers can point to an item
item* p1;
item* p2;
p1 = stackPtr;
//p1 either pointing to top of stack or to NULL
//while p1 are pointing to top of the stack
//here we going to delete the whole stack
while(p1 != NULL)
{
p2 = p1; //point pointer p2 to the top of the stack
p1 = p1->prev;
//let p1 point to item below the top
p2->prev = NULL;
//p2 is top item, p2->prev is the top item's
pointer(it points to previous
//item, i.e. part that link the
nodes) and let it point to NULL. i.e. disconnect the
//top item from the stack
delete p2;
//delete top item
}
}
void Stack::Push(string name, int value)
{
item* n = new item; //create a new item and create an item pointer(n) and
let
//pointer 'n' point to this item
//place arguments into the created item
n->name = name;
n->value = value;
//if stack is empty
if(stackPtr == NULL)
{
stackPtr = n; //make the new item the top of the stack
//the stack now only consist of the newly
created item
//stackPtr now represents the newly
created item
stackPtr->prev = NULL;
//stackPtr now represents the newly
created item. so
//stackPtr->prev is the
item's link part(i.e.) the pointer that
//point the the previous
item. No previous items thus make it NULL
}
else//the stack exists
{
//let the newly created item's link part point to the
//top item. Now it makes a chain. Remember a stack is a chain just
like a
//linked list
n->prev = stackPtr;
stackPtr = n; //let stack pointer point to newly created item.
Remember newly
//created item goes on top, stackPtr points to
the top
}
}
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
void Stack::ReadItem(item* r)
{
//r will be pointing to some item
cout << "---------------\n";
cout << "name: " << r->name << endl;
cout << "value: " << r->value << endl;
cout << "---------------\n";
}
//remove top item on the stack and print content of the removed item
void Stack::Pop()
{
//if stack is empty, remember if stack empty then stackPointer points to
NULL
if(stackPtr == NULL)
{
cout << "There is nothing in the stack" << endl;
}
else
{
item *p = stackPtr; //create item pointer and let it point to top
item(to what
//stackPtr is pointing towards
cout << "The following item was removed:" << endl;
ReadItem(p); //display content of the top item, i.e. item that is
gona be popped
//now we know what we are removing
stackPtr = stackPtr->prev; //let pointer point to the item below the
top item, i.e. the new top item
//remember p is pointing to the top
p->prev = NULL;
//separates the top item from the stack, let top
item's link part point to NULL
delete p;
//delete the top node(p represents the top node)
}
}
void Stack::Print()
{
item* p = stackPtr; //2 cases: case1: stack empty->p point to NULL
//
case2: stack non empty->p point
to top item
//while p is not null, i.e. while there are still items to print
while(p != NULL)
{
ReadItem(p); //print the content in item that p is pointing towards
p = p->prev; //make p point to item below the item that p is
currently pointing towards
}
//so this will print all the items. This covers both cases
}
Book’s example:
To implement a stack we need the following operations:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
• initializeStack—Initializes the stack to an empty state.
• isEmptyStack—Determines whether the stack is empty. If the stack
is empty, it returns the value true; otherwise, it returns the value
false.
• isFullStack—Determines whether the stack is full. If the stack is full,
it returns the value true; otherwise, it returns the value false.
• push—Adds a new element to the top of the stack. The input to
this operation consists of the stack and the new element. Prior to
this operation,
the stack must exist and must not be full.
• top—Returns the top element of the stack. Prior to this operation,
the stack must exist and must not be empty.
• pop—Removes the top element of the stack. Prior to this
operation, the stack must exist and must not be empty.
The stackADT class defined these operations. Note these operations
are all pure virtual functions, thus we only write a header file for
stackADT class, because pure virtual function doesn’t have a body
and it will get overridden by an inheriting class’ function
Because all the elements of a stack are of the same
type, a stack can be implemented as either an array or
a linked structure.
Implementation of stacks as Arrays:
The top of the stack is the index of the last element added to the
stack.
We use the class stackType to implement a stack as an array.
We use a pointer to dynamically allocate arrays, so we will leave it for the user
to specify the size of the array (that is the stack size). We assume the default
stack size is 100 thus in constructor we have a default parameter.
We have the 3 variables in the class:
int maxStackSize; //variable to store the maximum stack size
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
int stackTop;
//variable to point to the top of the stack
//it indicates how many elements in the stack
Type *list; //pointer to the array that holds the stack elements
//i.e. list is the stack
stacktop can range from 0 to maxStackSize. The index of the top element will
always be stackTop-1
Notice the stack still exist even if it is empty. But if the stack is unused then the
stack is empty and stackTop is zero
Linked Implementation of Stacks:
We use the class linkedStackType to implement a stacks of links. The
class derives from stackADT
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Stack as derived from the class
unorderedLinkedlist
The class linkedStackType is a stack implemented as an
unorderedLinkedList
Here are the functions:
void initializeStack();
bool isEmptyStack() const;
bool isFullStack() const;
void push(const Type& newItem);
Type top() const;
void pop();
Here is an inheriting diagram to make things easier:
linkedListType -> unorderedLinikedList -> linkedStackType
Using a stack to print a linked list
backwards:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
It’s quite easy. Use current pointer to traverse the linked list and as
you traverse the list push each element on the stack.
current = first; //Line 1
while (current != NULL) //Line 2
{
stack.push(current); //Line 4
current = current->link; //Line 5
}
The last element in the linked list will be on top of the stack
Then simply set current to top of stack, print out current’s info, i.e.
top element, and then pop the top. Repeat this until stack is empty
while (!stack.isEmptyStack()) //Line 7
{
current = stack.top(); //Line 9
stack.pop(); //Line 10
cout << current->info << " "; //
}
STL stack class (stack in the library)
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Operations in this class:
Queues
Same as stack, but it’s FIFO- First In First Out structure
Insertion happens at one end and deletion happens from the
other end.
Insertion happens at the rear or tail and removal happens
from the front or head
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Definition: List(or collection) with restriction that insertion
can be performed at one end(rear) and deletion can be
performed at the end(front)
Just like with stacks we have the 2 fundamental insert and
removal operations.
Insertion is called addQueue and removal is called deleteQueue
Here are the rest of the functions:
initializeQueue - Initializes the queue to an empty state.
isEmptyQueue -Determines whether the queue is empty. If the
queue is empty, it returns the value true; otherwise, it returns the
value false
isFullQueue - Determines whether the queue is full. If the queue is
full, it returns the value true; otherwise, it returns the value false.
Front - Returns the front, that is, the first element of the queue. Prior
to this operation, the queue must exist and must not be empty.
Back -Returns the last element of the queue. Prior to this operation,
the queue must exist and must not be empty.
addQueue - Adds a new element to the rear of the queue. Prior to
this operation, the queue must exist and must not be full.
deleteQueue - Removes the front element from the queue. Prior to
this operation, the queue must exist and must not be empty.
Example:
// CPP code to illustrate
// Queue in Standard Template Library (STL)
#include <iostream>
#include <queue>
using namespace std;
// Print the queue
void showq(queue <int> gq)
{
queue <int> g = gq;
while (!g.empty())
{
cout << '\t' << g.front();
g.pop();
}
cout << '\n';
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
}
// Driver Code
int main()
{
queue <int> gquiz;
gquiz.push(10);
gquiz.push(20);
gquiz.push(30);
cout << "The queue gquiz is : ";
showq(gquiz);
cout << "\ngquiz.size() : " << gquiz.size();
cout << "\ngquiz.front() : " << gquiz.front();
cout << "\ngquiz.back() : " << gquiz.back();
cout << "\ngquiz.pop() : ";
gquiz.pop();
showq(gquiz);
// We can also use front and back as
// iterators to traverse through the queue
count<<"Using iterators : ";
for(auto i = gquiz.front(); i != gquiz.back(); i++)
{
count<< i <<" ";
}
return 0;
}
Linked Lists
Uses pointers to organize and process data in lists
unlike arrays where data in memory is stored sequentially, with linked
lists data is not stored sequentially in memory
It’s a collection of components called nodes.
Every node, except the last one, contains the address of the next node.
Every node has 2 components: The data and the address of the next
node, called the link.
The address of the 1st node, called the head is stored in separate
location.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Def: A list of nodes in which order of the nodes is determined by the
address, called the link, stored in each node.
The arrow in each node indicates that the address of the node it is
pointing is stored in the node, i.e. address of next node is stored in the
right part of the node. Downward arrow in last node indicates this link
field in NULL, i.e. pointing to nothing.
Here is a better understanding of what is happening. The next node’s address
is stored inside the previous nodes link section.
Note: The head has the address value of the 1st node. Node 1 is at address
1200. Link components of 1st node contain address of 2nd node.
How to declare linked list in code:
Each node of a linked list has two components thus each node we declare as
struct or class. Each link list can hold different data types, thus the data type of
the data component is dependent on what type of data the list is holding.
However the link component of each node is a pointer. The type of the pointer
is the node type, i.e. struct or class type since it is pointing to that. Remember
int pointer point to int, double pointer point to double, thus struct pointer
point to struct
SYNTAX for creating linked list:
struct nodeType
{
data_type_that_you_want_list_to_hold var_name;
nodeType *link;
};
Example:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
struct nodeType
{
int info;
nodeType *link;
};
SYNTAX for declaring:
nodeType *head;
Note head points to the struct which have
2 components, thus it’s pointing to a node. Remember head is
not a node!!! head is a pointer that CAN point to a node. That
is why in the following picture head is just represented by
one block
Assume we have created and declared the linked list NodeType and
nodeType *head;
:
1st node
2nd node
How to access the values:
Note: Remember that when you have declared a class or struct and you make
an object pointer from that struct or class. Then to access a data variable in
that class or struct you go object_pointer_name->data_member . The -> is the
pointer separator. Use it instead of the dot when object is a pointer
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
How does this work: A pointer points to a variable or class. And remember
that the pointer name can be used now instead of the variable name. So the
name head represents the 1st node. So going ‘head->info’ will get the 1st node’s
info member which have the value of 17.
So always when you go pointer->member then think of it being the
class’(or struct) member that the pointer is pointing to.
So head->link represents the 2nd node. head represents the 1st
node, 1st node link represents the 2nd node. Always think of variable
that pointer is pointing towards
Remember head is address of the 1st node
head will give 2000, because name of the pointer gives value of address that it
is pointing to. Head is pointing to address 2000. (Look in picture).
head->data_variable_name will give you value of the data variable.
Thus head->info give you value of the info component of what head is pointing
to.
head->link will give you value of link component of what head is pointing to, so
look in picture. link’s value of 1st node is 2800, i.e. address it’s pointing to
head->link->info: “head->link” will give you value of link component of what
head is pointing to(1st node), so in other words it will show you to what the 1st
node is pointing to. It’s pointing to the 2nd node(at address 2800). Then
head->link->info will give you what 2nd node is pointing to, i.e. to the 3rd
node(3rd node’s address).
Suppose we declare:
nodeType *current;
//current is the same type as head
current = head;
//copies the value of head(address of 1st
node, i.e. current is pointing to 1st node) and give it to
current. Thus let current point to same thing that head is
pointing towards, i.e. 1st node
current = current->link; //current points to 1st node, now
current->link returns what current’s link is pointing to(the
2nd node). Then it updates what current is pointing to. Thus
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
current now points to 2nd node.
current = current->link; //Thus, this is used to advance in a
linked list. Remember pointer(current) on left side of equal
sign means pointer itself and on right hand side it meansthe
variable it’s pointing to
current->link->info; //returns 63, so pointer_name->link will
go to the next node
Moving through a linked list:
The operations are:
Search the list
Insert an item
Delete an item
These operations require us to move through(traverse) the list.
We cannot use the head pointer to traverse the list because if we use the head
we would lose the nodes of the list. (remember head stores address of 1st
node), thus we would lose the address of the 1st node and won’t be able to get
it again. Also, the list only moves in one direction. Thus we use the current
pointer to traverse the list.
The following code traverse the linked list:
current = head;
//let current point to what head is
pointing to(1st node)
//while current’s value is not NULL(i.e. has the value of the
last node) then move on
while (current != NULL)
{
current = current->link; //move current to the next node
}
For example, suppose that head points to a linked list of
numbers. The following code outputs the data stored in each
node:
current = head;
while (current != NULL)
{
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
cout << current->info << " "; //print out the info
component of what current is pointing
current = current->link; //move current to next node
}
Suppose we have this linked list:
Suppose we want to insert node after node with 65 in its info
variable.
nodeType *head, *p, *q, *newNode; //new node is a pointer of
the type nodeType that will point to new node
newNode = new nodeType; //create a node(remember newNode class
type represent a new node), but we creating dynamic node and
let pointer newNode point to it. Now we can refer to the new
node with the pointer NewNode
newNode->info = 50; //store 50 in the new node’s info member
variable
newNode->link = p->link; //p is pointing to node with 65, thus
p can be seen as the 65 node. Thus let 65’s link(i.e. what
node 65 is pointing to(34) and give that to newNode’s link. So
basically let newNode point to 34 node. If you have
something->link then it is the node of what something is
pointing to
p->link = newNode; //p is node65, so we going node65->link
which is what node65 is pointing to. Thus let node65 point to
the new node. Remember that listing pointer on the right hand
side of = sign returns the address of what the pointer is
pointing to, so it’s returning address of the newNode
On the left hand side of equal sign pointer name means the
node it is pointing to. On the right hand side it means the
node it is pointing towards. Look @ newNode->link = p->link;
newNode->link; newNode is pointer itself, then newNode->link
the what the pointer is pointing to(link is always next one).
p is the node p is pointing to(node with 65). Then p->link is
the next node, i.e. node with 34
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
To summarize
To insert a node between two node’s we have to:
We have to use a pointer(p) that is pointing to the left node to which
you want to enter the node.
make a new node by creating dynamic object and let the pointer point
to it.
Then we have to let the new node point to what p’s node(node that p
point’s to) is pointing to
Then let p’s node point to the new node
Using 2 pointers we can simplify the insertion:
Adding node between p and q, i.e. between 65 and 34.
p->link = newNode; //pointer name(p) on either side
represents what it is pointing to, so p is representing
node65. However on left side it represents the node and on the
right side it will return it’s address Thus let node65 point
to newNode
newNode->link = q;
to, i.e. to 34
//let newNode point to what q is pointing
The order of these does not matter
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Deletion:
With deletion we need a pointer to the node that gets deleted so that we can
delete the node from memory after we have removed it from the list.
Here we have to delete node34 because it still occupies memory. but now we
can’t access it. Thus we need a pointer to point to it before we remove it from
the list. Here is the code to delete the node34 using the pointers p and q:
q = p->link;
//let q point to what node65 is pointing to. So
we let q point to the node that we going to delete
p->link = q->link; //let node65 point to what node34 is
pointing to, i.e. node76. Note: that p->link on left side of =
is changing link of node65(what the node will point to) and
q->link is returning the value of q’s link(which is what
q(node34) is pointing to, i.e. q is pointing to node76)
delete q; //delete node that q is pointing to, i.e. node34
Building a linked list:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Two cases: - Forward building: Adding new nodes at end
-Backward building: Adding new nodes at start
Forward building:
Suppose we want to build a linked list and node Type struct has been declared.
Also suppose we want to build a list with this data: 2 15 8 24 34
We need 3 pointers to build the list:
-one to point to 1st node
-one to point to last node
-and one to create new node
Here is the code:
nodeType *first, *last, *newNode; //declare the 3 pointers we
use to build list
int num; //variable that will hold the data values
//both nodes points to nothing
first = NULL;
last = NULL;
cin >> num; //read and store a number in num
newNode = new nodeType; //allocate memory of type nodeType
and store the address of the allocated memory in newNode, i.e.
create a new node
newNode->info = num; //copy the value of num into the
//info field of newNode
newNode->link = NULL; //let new node point to NULL, i.e. it’s
going to be last node. Remember doing thus will let the arrow
point down, see picture
//if first is NULL, the list is empty thus make first and last
point to newNode
if (first == NULL)
{
first = newNode;
last = newNode;
}
else //list is not empty
{
last->link = newNode; //insert newNode at the end of the
list, let last’s link(i.e. the node that last is pointing to,
let it point to the new node being inserted at the end
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
last = newNode; //set the last pointer to point to the
new inserted node which becomes the last node
}
Notice we need to include a while list to repeat the addition of a list. Also we
include a function to build the list. This function returns the pointer that points
to the 1st node of the list:
nodeType* buildListForward()
//we returning first, and first is
of type nodeType*, thus func need to be of this type
{
nodeType *first, *newNode, *last;
int num;
cout << "Enter a list of integers ending with -999."
<< endl;
//this function(while loop) ends when user type in -999
cin >> num;
first = NULL;
while (num != -999)
//while num is not -999
{
newNode = new nodeType;
//reserve mem for a new node and
let new node point to it
newNode->info = num; //give value that user entered to newNode
newNode->link = NULL; //let new node point to NULL, it’s gona
be last node
//if list is empty(we haven’t entered a new node yet)
if (first == NULL)
{
first = newNode; //let 1st node point to the new node
last = newNode;
}
//list is not empty
else
{
last->link = newNode; //let last node point to newNode
last = newNode; let last pointer point to newNode which
becomes the last node
}
cin >> num;
} //end while
return first;
//return pointer that points to 1st node of the
linked list
} //end buildListForward
Forward building:
We do not need to know end of list, thus we do not need ‘last’ pointer since
we adding nodes in the front
nodeType* buildListBackward()
{
nodeType *first, *newNode;
int num;
cout << "Enter a list of integers ending with -999."
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
<< endl;
cin >> num;
first = NULL;
while (num != -999)
{
newNode = new nodeType; //create a node
newNode->info = num; //store the data in newNode
newNode->link = first; //put newNode at the beginning
//of the list, let newNode point to what 1st is pointing
to, 1st will be pointing to node after the entered node
first = newNode; //update the head pointer of
//the list, that is, first
cin >> num; //read the next number
}
return first;
} //end buildListBackward
Linked lists as ADT(Abstract data types)
There are two types of linked lists: Sorted and unsorted. Their search, insert,
delete operations differ from one another.
We will define a class: class linkedListType to implement the basic operations
on a linked list. Then using inheritance we derive two classes:
unorderedLinkedList and orderedLinkedList from linkedListType.
Recall that a template is a way of defining a general type where we can use
any type we want:
Some code to help you remember:
template <typename T>
used as a general type
//declaring a template and naming it T, now T can be
int main()
{
T intVar =5;
T doubleVar = 6.7;
We can also declare a class template as follows, remember class is a special type:
template <class type> class class-name {
e.g.
template <class T>
class Stack {
private:
vector<T> elems;
// elements
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
public:
void push(T const&);
// push element
void pop();
// pop element
T top() const;
// return top element
bool empty() const {
// return true if empty.
return elems.empty();
}
};
int main() {
try {
Stack<int>
intStack; // stack of ints, here it creates object of
class stack, but with all the T in the class being replaced with int’s
Back to linked lists:
Definition of the node:
template <class Type>
//declare a class template. The
identifier “Type” is a general type
struct nodeType
{
Type info;
nodeType<Type> *link;
//link is pointer of type
nodeType, thus it points to a struct, but with Type being any
type. Thus info can be of any type, even a class type
};
Member variables of the class linkedListType
protected:
int count; //variable to store the number of elements in
the list
nodeType<Type> *first; //pointer to the first node of the
list
nodeType<Type> *last; //pointer to the last node of the
list
Linked List Iterators:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Iterators are used to traverse a list, thus we use iterator to traverse a
linked list
An iterator IS an object that produces each element of a container(such
as linked list) one element at a time.
Two most common iterators are ++(increment operator) and
*(dereferencing operator). The increment operator advances the
iterator to the next node and dereference operator returns info of the
current node.
NOTE: An iterator is an object, thus we define a class to create iterators
to objects of the class linkedListType
Here is the code to create the iterator class:
template <class Type>
class linkedListIterator
//create template class and a class with
name of linkedListIterator
{
public:
linkedListIterator();
//Default constructor
//Postcondition: current = NULL;
linkedListIterator(nodeType<Type> *ptr);
//Constructor with a parameter.
//Postcondition: current = ptr;
Type operator*();
//Function to overload the dereferencing operator *.
//Postcondition: Returns the info contained in the node.
linkedListIterator<Type> operator++();
//Overload the preincrement operator.
//Postcondition: The iterator is advanced to the next node.
//remember the type is the class itself, because with the
overloading the ++ operator we are moving on to the next object t of
type ‘linkedListIterator<Type>’
bool operator==(const linkedListIterator<Type>& right) const;
//Overload the equality operator.
//Postcondition: Returns true if this iterator is equal to
// the iterator specified by right, otherwise it returns
// false.
bool operator!=(const linkedListIterator<Type>& right) const;
//Overload the not equal to operator.
//Postcondition: Returns true if this iterator is not equal to
// the iterator specified by right, otherwise it returns
// false.
private:
nodeType<Type> *current; //pointer to point to the
//current node in the linked list
};
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Here is the code for the definitions of these functions:
template <class Type>
linkedListIterator<Type>::linkedListIterator()
{
current = NULL; //set current pointer to NULL
}
template <class Type>
linkedListIterator<Type>::linkedListIterator(nodeType<Type> *ptr)
{
current = ptr; //when user create an object and give it an
argument then the current pointer will point to that pointer in the
argument.
}
template <class Type>
Type linkedListIterator<Type>::operator*()
{
return current->info; //return the info component’s value of
current pointer
}
template <class Type>
linkedListIterator<Type> linkedListIterator<Type>::operator++()
{
current = current->link;
//move current to the next node
return *this;
//return the that we are dealing with, but
because we moved pointer to the next one we return next node
/*this?
}
template <class Type>
bool linkedListIterator<Type>::operator==(const
linkedListIterator<Type>& right) const
{
return (current == right.current);
return true if the
pointers point to the same node
}
template <class Type>
bool linkedListIterator<Type>::operator!=
(const linkedListIterator<Type>& right) const
{
return (current != right.current);
}
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Here is the code for the class that defines the basic properties of a linked list as
an ADT:
---------Before we do the code we need to know virtual functions:
Virtual functions is a way of overriding the base class’s function even if you are using a
pointer that has been declared of the base class. So when virtual is used then the derived
class’s function will get executed
class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
class derived:public base
{
public:
void print ()
{ cout<< "print derived class" <<endl; }
void show ()
{ cout<< "show derived class" <<endl; }
};
int main()
{
base *bptr;
//note that bptr is pointing to the base class
derived d;
bptr = &d;
//Note we have a base class object pointer that points to
a derived class object
//virtual function
bptr->print(); //output: print derived class. But you expected it to
print the base classes function, but because virtual is used it overrides
base classes function
// Non-virtual function
bptr->show(); //output: show base class
}
------------Here is the code for class that defines basic properties of a linked list as ADT.
Remember the orderedLinkedList and unorderedLinkedList classes are going
to inherit from this class(linkedListType) so this class hold the properties that
both of them have.
template <class Type>
class linkedListType
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
{
public:
const linkedListType<Type>& operator=
(const linkedListType<Type>&);
//Overload the assignment operator.
void initializeList();
//Initialize the list to an empty state.
//Postcondition: first = NULL, last = NULL, count = 0;
bool isEmptyList() const;
//Function to determine whether the list is empty.
//Postcondition: Returns true if the list is empty, otherwise
// it returns false.
void print() const;
//Function to output the data contained in each node.
//Postcondition: none
int length() const;
//Function to return the number of nodes in the list.
//Postcondition: The value of count is returned.
void destroyList();
//Function to delete all the nodes from the list.
//Postcondition: first = NULL, last = NULL, count = 0;
Type front() const;
//Function to return the first element of the list.
//Precondition: The list must exist and must not be empty.
//Postcondition: If the list is empty, the program terminates;
// otherwise, the first element of the list is returned.
Type back() const;
//Function to return the last element of the list.
//Precondition: The list must exist and must not be empty.
//Postcondition: If the list is empty, the program
// terminates; otherwise, the last
// element of the list is returned.
virtual bool search(const Type& searchItem) const = 0;
//This is a pure virtual function, it doesn’t go in the .cpp file
and you add = 0 to it. This function WILL get overridden by
inherited class’ function
//Function to determine whether searchItem is in the list.
//Postcondition: Returns true if searchItem is in the list,
// otherwise the value false is returned.
//Note: the = 0 is the default value the function returns, i.e. it
is false
virtual void insertFirst(const Type& newItem) = 0;
//Function to insert newItem at the beginning of the list.
//Postcondition: first points to the new list, newItem is
// inserted at the beginning of the list, last points to
// the last node in the list, and count is incremented by
// 1.
virtual void insertLast(const Type& newItem) = 0;
//Function to insert newItem at the end of the list.
//Postcondition: first points to the new list, newItem is
// inserted at the end of the list, last points to the
// last node in the list, and count is incremented by 1.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
virtual void deleteNode(const Type& deleteItem) = 0;
//Function to delete deleteItem from the list.
//Postcondition: If found, the node containing deleteItem is
// deleted from the list. first points to the first node,
// last points to the last node of the updated list, and
// count is decremented by 1.
linkedListIterator<Type> begin();
//Function to return an iterator at the beginning of the
//linked list.
//Postcondition: Returns an iterator such that current is set
// to first.
linkedListIterator<Type> end();
//Function to return an iterator one element past the
//last element of the linked list.
//Postcondition: Returns an iterator such that current is set
// to NULL.
linkedListType();
//default constructor
//Initializes the list to an empty state.
//Postcondition: first = NULL, last = NULL, count = 0;
linkedListType(const linkedListType<Type>& otherList);
//copy constructor
~linkedListType();
//destructor
//Deletes all the nodes from the list.
//Postcondition: The list object is destroyed.
protected:
int count; //variable to store the number of list elements
nodeType<Type> *first; //pointer to the first node of the list
nodeType<Type> *last; //pointer to the last node of the list
private:
void copyList(const linkedListType<Type>& otherList);
//Function to make a copy of otherList.
//Postcondition: A copy of otherList is created and assigned
// to this list.
};
Here is the class linkedListType in a UML diagram for easier reading
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
We are going to derive the classes unorderLinkedList and orderedLinkedList from this class
thus the instance variable’s first and last are protected. Protected means the inheriting
classes can use these members
The initializeList function actually destroys the list since the constructor and copy
constructor actually initialize the list. So we call destroyList function in initializeList.
With print() function we print the list. We can’t use first pointer to traverse the list
otherwise list will be lost thus we declare current pointer and use it to traverse the list
length function return size of the list thus we just return count which is number of nodes.
Retrieve data of first node function:
template <class Type>
Type linkedListType<Type>::front() const
{
assert(first != NULL);
if the list is empty the program gets
terminated
return first->info; //return the info of the first node
}
Note we return the data in the node which is of general type
thus function starts with Type
Begin and end functions:
Begin returns an iterator to the 1st node, i.e. creates an object of type
‘linkedListIterator<Type>’(which is iterator object) and then let current point to first
template <class Type>
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
linkedListIterator<Type> linkedListType<Type>::begin()
{
linkedListIterator<Type> temp(first);
return temp;
}
template <class Type>
linkedListIterator<Type> linkedListType<Type>::end()
{
linkedListIterator<Type> temp(NULL);
return temp;
}
For destructor function we just call destroyList function which deallocated the memory
which destroys the list
template <class Type>
linkedListType<Type>::~linkedListType() //destructor
{
destroyList();
}
Copying the list:
This function makes an copy of the linked list sent by the argument:
template <class Type>
void linkedListType<Type>::copyList
(const linkedListType<Type>& otherList)
{
nodeType<Type> *newNode; //pointer to create a node
nodeType<Type> *current; //pointer to traverse the list
if (first != NULL) //if the list is nonempty, make it empty
destroyList();
if (otherList.first == NULL) //otherList is empty
{
first = NULL;
last = NULL;
count = 0;
}
else
{
current = otherList.first; //current points to the
//list to be copied
count = otherList.count;
//copy the first node
first = new nodeType<Type>; //create the node
first->info = current->info; //copy the info
first->link = NULL; //set the link field of the node to NULL
last = first; //make last point to the first node
current = current->link; //make current point to the next
// node
//copy the remaining list
while (current != NULL)
{
newNode = new nodeType<Type>; //create a node
newNode->info = current->info; //copy the info
newNode->link = NULL; //set the link of newNode to NULL
last->link = newNode; //attach newNode after last
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
last = newNode; //make last point to the actual last
//node
current = current->link; //make current point to the
//next node
}//end while
}//end else
}//end copyList
Now for the unordered Linked Class: Note it’s going to derive from linkedListType
The deletingNode function is quite advanced. We have 3 cases with case 3
having 2 sub cases:
Case 1: List is empty, then we output error message
Case 2: List is not empty and node to be deleted is 1st node.
Case 3a: Node to be deleted is not 1st node, but somewhere in the list, but not
the last node
Case 3b: The node to be deleted is last node
Case 4: Node to be deleted is not in the list
We handle cases 2, 3 and 4 together because they all require us to traverse through the list.
We also use 2 pointers, current pointer to traverse through the list and trailCurrent which is
pointer before current pointer
The code:
template <class Type>
void unorderedLinkedList<Type>::deleteNode(const Type& deleteItem)
{
nodeType<Type> *current; //pointer to traverse the list
nodeType<Type> *trailCurrent; //pointer just before current
bool found;
if (first == NULL) //Case 1; the list is empty.
cout << "Cannot delete from an empty list."
<< endl;
else //here we start other cases, case 2, 3 and 4
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
{
if (first->info == deleteItem) //Case 2, delete 1st node
{
current = first;
first = first->link; //set 1st to point to 2nd node
count--;
//decrement number of nodes
if (first == NULL) //the list has only one node
last = NULL;
delete current; //we use current to delete the node
}
else //else, node to be deleted is not 1st node thus
search the list for the node with the given info actually
start of case 3.
{
found = false;
trailCurrent = first; //set trailCurrent to point
//to the first node
current = first->link; //set current to point to
//the second node
while (current != NULL && !found)
{
if (current->info != deleteItem)
{
trailCurrent = current;
//move trail
one node on
current = current-> link; //move
current to next node
}
else
found = true;
}//end while
if (found) //Case 3; if found, delete the node
{
trailCurrent->link = current->link; //set the
node trail is pointing to(i.e. the node before the
one we want to delete), set it to point to the node
after current
count--;
if (last == current) //node to be deleted was
//the last node
last = trailCurrent; //update the value
of last
delete current; //delete the node from the
list
}
else //case 4, we have not found the node in the
list
cout << "The item to be deleted is not in "
<< "the list." << endl;
}//end else
}//end else
}//end deleteNode
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Header File of Unordered Linked List:
The definition of the class linkedListType is in the file linkedList.h
#ifndef UnorderedLinkedList_H_
#define UnorderedLinkedList_H_
#include "linkedList.h"
using namespace std;
template <class Type>
class unorderedLinkedList: public linkedListType<Type>
{
public:
bool search(const Type& searchItem) const;
//Function to determine whether searchItem is in the list.
//Postcondition: Returns true if searchItem is in the list,
// otherwise the value false is returned.
void insertFirst(const Type& newItem);
//Function to insert newItem at the beginning of the list.
//Postcondition: first points to the new list, newItem is
// inserted at the beginning of the list, last points to
// the last node, and count is incremented by 1.
void insertLast(const Type& newItem);
//Function to insert newItem at the end of the list.
//Postcondition: first points to the new list, newItem is
// inserted at the end of the list, last points to the
// last node, and count is incremented by 1.
void deleteNode(const Type& deleteItem);
//Function to delete deleteItem from the list.
//Postcondition: If found, the node containing deleteItem
// is deleted from the list. first points to the first
// node, last points to the last node of the updated list,
// and count is decremented by 1.
};
template <class Type>
bool unorderedLinkedList<Type>::search(const Type& searchItem) const
{
nodeType<Type> *current; //pointer to traverse the list
bool found = false;
current = first; //set current to point to the first
//node in the list
while (current != NULL && !found) //search the list
if (current->info == searchItem) //searchItem is found
found = true;
else
current = current->link; //make current point to
//the next node
return found;
}//end search
template <class Type>
void unorderedLinkedList<Type>::insertFirst(const Type& newItem)
{
nodeType<Type> *newNode; //pointer to create the new node
newNode = new nodeType<Type>; //create the new node
newNode->info = newItem; //store the new item in the node
newNode->link = first; //insert newNode before first
first = newNode; //make first point to the actual first node
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
count++; //increment count
if (last == NULL) //if the list was empty, newNode is also
//the last node in the list
last = newNode;
}//end insertFirst
template <class Type>
void unorderedLinkedList<Type>::insertLast(const Type& newItem)
{
nodeType<Type> *newNode; //pointer to create the new node
newNode = new nodeType<Type>; //create the new node
newNode->info = newItem; //store the new item in the node
newNode->link = NULL; //set the link field of newNode to NULL
if (first == NULL) //if the list is empty, newNode is
//both the first and last node
{
first = newNode;
last = newNode;
count++; //increment count
}
else //the list is not empty, insert newNode after last
{
last->link = newNode; //insert newNode after last
last = newNode; //make last point to the actual
//last node in the list
count++; //increment count
}
}//end insertLast
template <class Type>
void unorderedLinkedList<Type>::deleteNode(const Type& deleteItem)
{
nodeType<Type> *current; //pointer to traverse the list
nodeType<Type> *trailCurrent; //pointer just before current
bool found;
if (first == NULL) //Case 1; the list is empty.
cout << "Cannot delete from an empty list."
<< endl;
else //here we start other cases, case 2, 3 and 4
{
if (first->info == deleteItem) //Case 2, delete 1st node
{
current = first;
first = first->link;
//set 1st to point to 2nd node
count--;
//decrement number of nodes
if (first == NULL) //the list has only one node
last = NULL;
delete current;
//we use current to delete the node
}
else //else, node to be deleted is not 1st node thus search the list
for the node with the given info actually start of case 3.
{
found = false;
trailCurrent = first; //set trailCurrent to point
//to the first node
current = first->link; //set current to point to
//the second node
while (current != NULL && !found)
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
{
if (current->info != deleteItem)
{
trailCurrent = current;
//move trail one node
on
current = current-> link; //move current to next
node
}
else
found = true;
}//end while
if (found) //Case 3; if found, delete the node
{
trailCurrent->link = current->link; //set the node
trail is pointing to(i.e. the node before the one we want to delete), set it to
point to the node after current
count--;
if (last == current) //node to be deleted was //the
last node
last = trailCurrent; //update the value of last
delete current; //delete the node from the list
}
else //case 4, we have not found the node in the list
cout << "The item to be deleted is not in "
<< "the list." << endl;
}//end else
}//end else
}//end deleteNode
#endif /* UnorderedLinkedList_H_ */
Ordered Linked Lists:
Remember we also derive the class orderedLinkedList form the class linkedListType.
Defining the class for orderedLinkedList:
template <class Type>
class orderedLinkedList: public linkedListType<Type>
{
public:
bool search(const Type& searchItem) const;
//Function to determine whether searchItem is in the list.
//Postcondition: Returns true if searchItem is in the list,
// otherwise the value false is returned.
void insert(const Type& newItem);
//Function to insert newItem in the list.
//Postcondition: first points to the new list, newItem
// is inserted at the proper place in the list, and
// count is incremented by 1.
void insertFirst(const Type& newItem);
//Function to insert newItem at the beginning of the list.
//Postcondition: first points to the new list, newItem is
// inserted at the beginning of the list, last points to the
// last node in the list, and count is incremented by 1.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
void insertLast(const Type& newItem);
//Function to insert newItem at the end of the list.
//Postcondition: first points to the new list, newItem is
// inserted at the end of the list, last points to the
// last node in the list, and count is incremented by 1.
void deleteNode(const Type& deleteItem);
//Function to delete deleteItem from the list.
//Postcondition: If found, the node containing deleteItem is
// deleted from the list; first points to the first node
// of the new list, and count is decremented by 1. If
// deleteItem is not in the list, an appropriate message
// is printed.
};
Note: orderedLinkedList have the same member functions as
unorderedLinkedList, but one extra function which is insert()
The insert function:
Again we use current and trailCurrent pointer to search the list.
The cases:
Case 1: The list is initially empty. The node containing the new item is the only node
and, thus, the first node in the list.
Case 2: The new item is smaller than the smallest item in the list. The new item goes at
the beginning of the list. In this case, we need to adjust the list’s head pointer—
that is, first. Also, count is incremented by 1.
Case 3: The item is to be inserted somewhere in the list.
Case 3a: The new item is larger than all the items in the list. In this case, the new
item is inserted at the end of the list. Thus, the value of current is NULL
and the new item is inserted after trailCurrent. Also, count is incremented
by 1.
Case 3b: The new item is to be inserted somewhere in the middle of the list. In this
case, the new item is inserted between trailCurrent and current.
Also, count is incremented by 1.
The function definition:
template <class Type>
void orderedLinkedList<Type>::insert(const Type& newItem)
{
nodeType<Type> *current; //pointer to traverse the list
nodeType<Type> *trailCurrent; //pointer just before current
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
nodeType<Type> *newNode; //pointer to create a node
bool found;
newNode = new nodeType<Type>; //create the node
newNode->info = newItem; //store newItem in the node
newNode->link = NULL; //set the link field of the new node
//to NULL
if (first == NULL) //Case 1
{
first = newNode;
last = newNode;
count++;
}
else
{
current = first;
found = false;
while (current != NULL && !found) //search the list
{
if (current->info >= newItem)
found = true;
else
{
//move both pointers to the next node
trailCurrent = current;
current = current->link;
}
}
if (current == first) //Case 2, i.e. node entered at
beginning, so current is at the 1st node. Remember current will
be at where new node is to be entered
{
newNode->link = first;
let newnode point to 1st
node
first = newNode; //let first pointer point to the
new node
count++;
increment number of nodes
}
else //Case 3, either insert node at end or in middle
{
trailCurrent->link = newNode;
//let trail ptr
point to the new node
newNode->link = current;
//let news node point to
current node. Enter the newnode between current and
trailcurrent
if (current == NULL) //if node to be entered at end
last = newNode;
count++;
}
}//end else
}//end insert
Doubly Linked Lists
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Same as Linked Lists except here each node has two pointers.
One pointer pointing to the next node and one pointer pointing
to the previous node(except the 1st node)
Thus it can traverse in either way
STL Sequence container:
There are 3 types: vector, deque and list.
Here we discuss list container.
A sequence container is a container that stores a sequence of
information
Lists are implemented as doubly linked lists
The definition of the class list and the definitions of the functions to
implement the various operations on a list, are contained in the header
file list, i.e.
#include <list>
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Ways to declare a list:
Note: listCont is the object name and you can put any type in place of
elemType so that the list will hold that type of data. elemType stand for
element type, i.e. the info the list holds.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Operations(functions) of a list
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Linked Lists with header and Trailer Nodes:
Remember the insertion and deletion functions of orderedLinkedList and
unorderedLinkedList. They were complicated. Thus to simplify we add Header
and Trailer nodes.
To simplify these algorithms we never insert an item before the 1st or last node
and to never delete the 1st node.
We can set up a node, called the header, at the beginning of the list
containing
a value smaller than the smallest value in the data set.
Similarly, we can set up a node, called the trailer, at the end of the list
containing a value larger than the largest value in the data set.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
These two nodes, header and trailer, serve merely to simplify the insertion and
deletion algorithms and are not part of the actual list. The actual list is
between these two nodes.
E.g. How to set up: Say nodes contain names.
Now header needs to be 1st node, thus it must have smallest value then the
rest. thus we chose its value as ‘A’.
Similarly we chose the trailer to be ‘zzzzzzzz’ Assume all names are max of 8
characters, thus our trailer must be 8, it can be more
Recursion
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
It’s a function calling itself.
We require a base case.
What is base case? It is an ending point for your function.
So 1st thing we need to do when writing a recursive function is to build a base
case.
e.g. Factorial function:
int factorial(int x)
{
if(x==1)
//base case-method to exit the recursive function
return 1;
else
{
return x*factorial(x-1);
//the call to the recursive function inside
the
//recursive function need to have an argument
//that is diffirent to the argument than the
//fucntion header, i.e. 'x-1' is diffirent to x
}
}
Direct and indirect recursion:
Direct: When function calls itself
Indirect: When a function calls another function and eventually
results in the original function call. E.g. function A calls function B
and B calls A. Here the function A is indirectly recursive.
Searching and Hashing
Using search algorithms you can do the following:
Determine whether a particular item is in the list
If the data is organized, find the location in the list where item is stored
Find the location of an item to be deleted.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Keys uniquely identify items in a set, thus we use the key for
searching, sorting, insertion, and deletion.
Analysis of an algorithm key comparisons refer to comparing the
key of the search item with the key of an item in the list.
Analysis also refers to performance of an algorithm.
Number of key comparisons refer to number of times the key of an
item is compared with the keys of the items in the list.
In this chapter we refer to the arrayListType class:
template <class elemType>
class arrayListType
{
public:
const arrayListType<elemType>& operator=
(const arrayListType<elemType>&);
bool isEmpty() const;
bool isFull() const;
int listSize() const;
int maxListSize() const;
void print() const;
bool isItemAtEqual(int location, const elemType& item) const;
void insertAt(int location, const elemType& insertItem);
void insertEnd(const elemType& insertItem);
void removeAt(int location);
void retrieveAt(int location, elemType& retItem) const;
void replaceAt(int location, const elemType& repItem);
void clearList();
int seqSearch(const elemType& item) const;
void insert(const elemType& insertItem);
void remove(const elemType& removeItem);
arrayListType(int size = 100);
arrayListType(const arrayListType<elemType>& otherList);
~arrayListType();
protected:
elemType *list; //array to hold the list elements
int length; //to store the length of the list
int maxSize; //to store the maximum size of the list
};
Sequential search
o Also called linear search
o Works the same for array-based and linked lists.
o it always start at the 1st element and continues until either the item
is found or the enter list is searched
The algorithm code:
template <class elemType>
int arrayListType<elemType>::seqSearch(const elemType& item) const
{
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
int loc;
bool found = false;
for (loc = 0; loc < length; loc++)
if (list[loc] == item)
{
found = true;
break;
}
if (found)
return loc;
else
return -1;
} //end seqSearch
The analysis:
Statements before and after loop executed only once, thus very
little computing time.
The statements in the for loop are repeated several times. Notice
each time in the for loop n the if statement we compare the keys.
Thus when analysing a search algorithm we count the number of
key comparisons, because this number gives us the most useful
info.
There are 2 cases:
case 1: Unsuccessful case: item is not in the list and the loop will
iterate as many times as there are items in the list/array.
case 2: Successful case: has 2 inner cases:
-item is in the 1st element we make one comparison. This is the
best case scenario.
-Item is in last element thus we make the we make as many
comparisons as there are elements. This is the worst case
scenario
We need an average for the 2 possible scenarios in the successful
case. To determine:
1. Consider all possible cases
2. Find the number of comparisons for each case
3. Add the number of comparisons and divide by the
number of cases
The formulae:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Notice the top is possible
cases. If target is 1st
element. 1 comparisons is
required. If target is 2nd
element 2 comparisons is
required, etc.
On average sequential search half the list. e.g. is list size is 10000, on
average 5000 comparisons are made.
Thus sequential search is not very efficiently for large lists.
Ordered Lists
A list is ordered if its elements are ordered according to some criteria
Elements are normally in ascending order.
We define two classes of array and linked list that we will use to define
ordered lists as ADT:
We will use the orderedLinkedList class from chapter 5:
template <class Type>
class orderedLinkedList: public linkedListType<Type>
{
public:
bool search(const Type& searchItem) const;
//Function to determine whether searchItem is in the list.
//Postcondition: Returns true if searchItem is in the list,
//
otherwise the value false is returned.
void insert(const Type& newItem);
//Function to insert newItem in the list.
//Postcondition: first points to the new list, newItem
//
is inserted at the proper place in the list, and
//
count is incremented by 1.
void insertFirst(const Type& newItem);
//Function to insert newItem at the beginning of the list.
//Postcondition: first points to the new list, newItem is
//
inserted at the beginning of the list, last points to the
//
last node in the list, and count is incremented by 1.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
void insertLast(const Type& newItem);
//Function to insert newItem at the end of the list.
//Postcondition: first points to the new list, newItem is
//
inserted at the end of the list, last points to the
//
last node in the list, and count is incremented by 1.
void deleteNode(const Type& deleteItem);
//Function to delete deleteItem from the list.
//Postcondition: If found, the node containing deleteItem is
//
deleted from the list; first points to the first node
//
of the new list, and count is decremented by 1. If
//
deleteItem is not in the list, an appropriate message
//
is printed.
};
We also define a class orderedArrayListType that stores an ordered array as an
ADT:
template <class elemType>
class orderedArrayListType: public arrayListType<elemType>
{
public:
orderedArrayListType(int size = 100);
//constructor
//...
//We will add the necessary members as needed.
private:
//We will add the necessary members as needed.
};
Binary search
o Much more efficient than sequential search.
o Can only be performed on an ordered list.
o uses the divide and conquer technique.
o The steps:
1. Compare target (search item) with middle element.
We work with indexes of array.
To do this we create 3 variable first, mid and last. To
calculate the middle we say: mid = (first+last) /2.
Initially first = 0 and last = length-1
2. If target is found terminate search. Else If search target
is less than the middle element of the list, then restrict
search to 1st half, else (if target > middle) restrict
search to second half.
An image of how it works:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
The code:
template<class elemType>
int orderedArrayListType<elemType>::binarySearch
(const elemType& item) const
{
int first = 0;
int last = length - 1;
int mid;
bool found = false;
while (first <= last && !found)
{
mid = (first + last) / 2;
if (list[mid] == item) //list[mid] is the value in the middle value
found = true;
else if (list[mid] > item) //restrict search to 1st half
last = mid - 1;
else //restrict search to 2nd half
first = mid + 1;
}
if (found)
return mid;
else
return -1;
}//end binarySearch
Note in the formulae mid = (first + last) / 2; Because mid is int it will
always truncate (throw away) the decimal and only be the integer value.
E.g.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Performance of binary search:
o Every iteration of the while loop cuts the size of the search list by
half.
o Thus to find how many times it iterates or cuts it in half we will see
how many times the size (n) can be divided by two, i.e. how many
2’s make up the value.
o E.g. if the size of list is 1024 = 210, thus at most 11 iterations of the
while loop to search through list with size of 1024. Note we took
the exponent and added 1, because it makes an extra last
comparison and then exits the while loop. A while loop makes 2
comparisons. Thus we multiply it by 2. Thus with a size of 1024
we make 22 comparisons.
o Suppose L is sorted list of size n. Suppose n is a power of 2, i.e. 𝑛 = 2𝑚 ,
m is positive integer. But remember we add 1 to the iterations so m+1 is
the maximum number of iterations. Also from = 2𝑚 , 𝑚 = 𝑙𝑜𝑔2 𝑛 .
Each iteration have 2 key comparisons. Thus maximum number of
comparisons is 2(m+1) = 2(𝑙𝑜𝑔2 𝑛 + 1) =
2𝒍𝒐𝒈𝟐 𝒏+2
Insertion into an ordered list
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
How to insert into ordered array:
To do this 1st we must find the place in the list where the item is to be
inserted
Then we slide the list elements one array position down to make room
for the item to be inserted.
Then insert the item.
Because list is ordered we use binary search to search for the item.
Then we use the insertAt() function of class arrayListType to insert the
item.
We can’t use previously written binary search since it returns -1 if item is
not find, but here we do not worry if the item is not found, we simply
want to add item.
Algorithm to insert the item:
1. Use an algorithm similar to binary search to find place
where the item is to be inserted
2. If the item is already in this list output error message, else
use function insertAt to insert the item in the list
Here is the function to do this:
//notice we are going to add it to the function
template <class elemType>
void orderedArrayListType<elemType>::insertOrd(const elemType& item)
{
int first = 0;
int last = length - 1;
int mid;
bool found = false;
if (length == 0) //the list is empty
{
list[0] = item;
length++;
}
else if (length == maxSize)
//list(array) is full
cerr << "Cannot insert into a full list." << endl;
else
{
//-----------------------------This part is the same as
normally binary search
while (first <= last && !found)
//search
{
mid = (first + last) / 2;
if (list[mid] == item)
found = true;
else if (list[mid] > item)
last = mid - 1;
else
first = mid + 1;
}//end while
//------------------------------if (found) //item to be inserted is in the list
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
cerr << "The insert item is already in the list. "
<< "Duplicates are not allowed." << endl; //this is
diffirent to normal binary search code, this will exit the program
else //also diffirent to normal binary search
{
if (list[mid] < item)
//if the item @ mid is
smaller than item then you have to increment mid to insert item @ correct
loaction
mid++;
insertAt(mid, item);
//this function will move
the rest of the elements onwards to make space for the new item. It will
insert the item @ position mid
}
}
}//end insertOrd
Adding the functions insertOrd and binary search algorithm to the class
orderedArrayListType:
template <class elemType>
class orderedArrayListType: public arrayListType<elemType>
{
public:
void insertOrd(const elemType&);
int binarySearch(const elemType& item) const;
orderedArrayListType(int size = 100);
};
Because the class orderedArrayListType is derived from the class
arrayListType, and the list elements of an orderedArrayListType are
ordered, we must override the functions insertAt and insertEnd of the
class arrayListType in the class orderedArrayListType. You need to
make these functions pure virtual functions by deleting the body in and
writing ‘=0’ after the function header in the class arrayListType. Then
also add the new body to orderedArrayListType.
Also override sequential search that it takes into account that the list is
ordered.
Here are the algorithm analysis of the 2 searches:
Hashing:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
o A search algorithm less than binary search, i.e. less than order
𝒍𝒐𝒈𝟐 𝒏
o It’s not comparison based like sequential and binary
o On average it is of order 1
o Hashing also requires the data to be organised in a special way.
We organize the data in a hash table denoted by HT.
o HT is stored in array.
o To determine if item with a key is in the table we apply a function
called h, i.e. the hash function to the key x. denoted by h(X).
Read h of X.
o h(X) gives us address of the target in the hash table
o Thus to determine if item is in table we look @ the entry HT[h(X)],
i.e. apply function and then the answer we get we apply to the
table.
o Suppose size of the hash table is m ,then 0 ≤ h(X) <m. I,e, answer
you will get is between 0 and max size of hash table
How to organize data in hash table:
o There are 2 ways of doing this.
o One is to store data within the hash table, i.e. in an array.
o The second the data is stored in a linked list and the hash table
is an array of pointers to those linked lists.
o Hash tables are normally divided into buckets, say b buckets:
HT[0], HT[1],…,HT[b-1].
o Each bucket can hold r items. Thus b x r = m where me is the
size of HT. Remember HT is an array. Generally r is 1 and each
bucket can hold one item.
o The has function h maps the key onto an integer t, that is
h(X) = t, such that 0 ≤ h(X) ≤ b-1
Note HT is array name. HT[0] is 1st element of hash table array, HT[1] is
2nd element.
E.g.:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Note % is the modulus operator.
The division method ( a way to hash the key to an address):
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Note: insertKey is a char array, i.e. a string. The for loop only converts
the char array to an integer value. It converts each character to an int
and then adding the integers, thus yielding the full string in an integer
value.
Collisions:
This says that is we map a key and we get an index in the hash table
that we have already got (like in the previous example where we get
HT[5] again) then it’s collision. Since we only dealing with bucket size of
1, if a collision occur then we also have an overflow since the bucket is
full and we can’t add more data into the bucket (i.e. Hash table element).
Collision resolution:
Two methods:
Open Addressing (also called closed hashing):
Data is stored within the hash table.
It gives the index (h(X)) for each key X where it is likely to be
stored in the table.
Common ways to implement it:
Linear probing:
o Suppose:
o If a collision occurs we start at location t and search the
array sequentially to find the next available array slot.
o We assume array is circular so we never stop. When
we reach end we go on to beginning. This is done with
% operator.
o The probe sequence
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
E.g.
The code:
//hIndex represent a hash table index
hIndex = hashFunction(insertKey);
//hashFunction uses the division
method to compute the address of the key, i.e. it returns h(X), given X.
h(X) is address of item in hash table(array). Note h(X) is the index of the
hash table. HT[hX] a specific variable in the hash table(HT)
found = false;
while (HT[hIndex] != emptyKey && !found) //while not found AND the
element in HT array is not empty i.e. that is a key in the element
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
if (HT[hIndex].key == key)
//HT[hIndex].key return key in HT
with indexd of hIndex, so if the key are similar then it means there are
duplicate keys and while loop will exit
found = true;
else
//else move hIndex onwards
hIndex = (hIndex + 1) % HTSize;
//%HTSize
ensures array is circular and if we @ end then we move on towards the start
if (found)
cerr << "Duplicate items are not allowed." << endl;
else
//hIndex have been moved on, so store key in the next
available element in the HT
HT[hIndex] = newItem;
Linear probing causes clustering that is more and more new keys
would likely be hashed to the array slots that are already occupied.
We can improve this method by adding constant, see p/515
Random probing:
This method uses a random number generator to find the next
available slot.
The ith slot in the probe sequence is:
So basically when collision occur, i.e. key is given index of HT
(h(X)) of already existing index, then we put this key in a random
generated index in the table. Instead of adding 1 we add random
value between 1 and HTSize-1
E.g.
Note: This means we if we hash another 26 (index position in HT) for a
key then this key will be placed in 28, if 28 is occupied then will be
placed in 31, if 31 is occupied it will be placed in index 34.
Rehashing:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
In this method we use a series of hash functions. IF a collision occurs for function h,
then we use another function say ℎ1 , and if this yields a collision then we use ℎ2 ,
and so on.
Quadratic Probing:
In this process if a collision occur at index t we linearly search the array
at index locations t+𝑖 2 , i = { 1,2,3,4,5…} to see if it’s empty to insert the
key.
In other words:
Note the next probe is +1 to the original, then he next probe is +4 to the
original, then the next is +9 to the original. I.e. store key in index 25 of
HT. If it is full then store it in index 26, if it is full in 29, etc.
Quadratic probing reduces primary clustering.
Generating the code:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Note that 𝑠𝑜𝑚𝑒𝑡ℎ𝑖𝑛𝑔2 = starting @ 1 then adding all the uneven
numbers and the last term is 2.i-1.
Also note 𝑖 2 = 1+3+5+7+…+ (2.i-1), to the adding t on both sides of =
sign yields:
t+𝑖 2 = t+1+3+5+7+…+ (2.i-1)
Then we add ‘% HTSize’ to it to account for array being a circle.
Remember t is index of HT where we found the collision.
Here is the code to compute the ith probe(i.e. the index to store the key
that caused a collision). Ith probe i.e.
//t is index of where the collision occured
int inc = 1;
int pCount = 0;
//probe count, how many times we probed or moved onto
the next element
while (p < i)
//p is a prime number
{
t = (t + inc) % HTSize;
//update t(index) to new position where we
need to store the key
inc = inc + 2;
//inc gets incremented by 2
//notice that t+i_squared = t+1+3+5+7... according to the formulae so we increment
inc by 2
pCount++;
//increment probe count
}
*** find out what p is in the code ****
The code to implement quadratic probing:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
There exist a problem that is 2 different keys are hashed to the same
position and this hash (position) already contain a key. Then both keys
will follow the same probe sequence, i.e. both will follow the quadratic
probing. This happens @ both random and quadratic probing, because
are functions of the home position( i.e. t where the collision occurred).
This is called secondary clustering.
A way to solve this is to use linear probing, with the increment value a
function of the key. This is called double hashing.
Double hashing:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
For a specific key you calculate h(X) and g(X). Then to find the probe
sequence, i.e. the places that key X will be placed you go h(X) + i *g(X).
Look at X1. 35 + 1 * 3 = 38
35 + 2 * 3 = 41
etc.
E.G.:
Process is:
-1st calculate position to store key using h(X).
-Then if position is filled then calculate ( h(X)+g(X) ) % HTSize and store
the key in this position. ( h(X)+g(X) ) % HTSize will give you the position
where to store it
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Deletion: Open addressing
We simply can’t just delete an item, say R1, by making the HT
array empty where the item is.
This is because say items R1 and R2 was hashed to the same
position, but R1 is inserted 1st in that position ( i.e. the home
address) then R2 contain the probe sequence of R1. The probe
sequence formulae of R2 contain info. of R1.
Thus if we make R1 empty then searching for R2 will be
impossible.
To solve this we create a special key to be stored in the key of the
items to be deleted.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
This special key indicates that this array slot is available for a new
item to be inserted, however during the search the search should
not terminate at this location.
A better solution is to create another array say indexStatusList of
type int of the same size as the hash table. Initialize each element
of this array to 0 which means corresponding element of hash
table is empty. For each entry into hash table set corresponding
position of Status array to 1. If you delete a value of hash table
then set corresponding element of Status table to -1.
E.g.
Sorting algorithms
We apply sorting algorithms to array-based lists or linked
lists.
The functions for sorting algorithms will be included in the class
arrayListType, i.e. the class that has the basic properties of an
array.
E.G. Say we include selection sort the class will look like this:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Types of sorts:
Selection sort: array-based lists
It works by finding the location of the smallest element in the
unsorted portion of the list and moves it to the top of the unsorted
portion of the list.
E.g.
After 1st iteration it will look like the list on the left hand side:
After 2nd iteration:
Note the unsorted list becomes 1 smaller after each swap.
Steps in selection sort:
1. Find location of smallest element in unsorted list
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
2. Swap the smallest element with beginning of unsorted list.
After each iteration the unsorted portion of the list will be list[0+i] to
list[length-1], i being the increment number.
We can use a for loop to do the steps:
This function return the smallest element in list[first] … list[last]
//this function will be used to search through the unsorted list
//we past it the start and end index of the unsorted lit
template <class elemType>
int arrayListType<elemType>::minLocation(int first, int last)
{
int minIndex;
//variable to store index of smallest value
minIndex = first; //set minIndex to 1st element
//loc will start in the for loop with the 2nd element of the list
//we increment location each time
for (int loc = first + 1; loc <= last; loc++)
if( list[loc] < list[minIndex])
//if element @
location < element @ minIndex
minIndex = loc;
//let loc be the new minIndex
return minIndex;
} //end minLocation
//return index of smallest value
The following function swaps the element with the given indexes:
Note: elemType stand for element type. temp = element @ index first.
Then let array position @ first get element @ position second.
Then let array position @ second get temp value which is element that
was @ first.
Now for selection sort function:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
template <class elemType>
void arrayListType<elemType>::selectionSort()
{
int minIndex;
for (int loc = 0; loc < length - 1; loc++)
{
minIndex = minLocation(loc, length - 1);
//this will return the index of the smallest element
//in the unsorted list, notice 'loc' will be incremented, because
//the unsorted list gets moves 1 onwards
swap(loc, minIndex);
//this swap the elements of location and index of the smallest value
//notice location will always be @ the start of the unsorted list
}
}
We put the selectionSort function in the public access modifier,
because we need to call it in main so it needs to be visible. We put
minLocation and swap functions in protected acces modifier,
because we don’t need to call it, but the member functions will use
the functions.
Look in the selectionSort program to see the entire program and
the testing.
analysis of selection sort:
A sorting algorithm makes key comparisons and moves data.
Thus the analysis of sorting algorithms, we look at the number of
comparison as well as the number of data movements.
Suppose length of the list is n.
The swap function:
o It does 3 item assignments and is the function executed n-1
times. Thus number of item assignments is 3(n-1)
o Its executed n-1 times due to:
for (int loc = 0; loc < length - 1; loc++)
{
minIndex = minLocation(loc, length - 1);
swap(loc, minIndex);
}
For loop goes from 0 to < than length -1, thus n-1 times
The minLocation function:
Key comparisons are made in this functions.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
For list of length n, the function makes n-1 key comparisons.
This is due to:
for (int loc = first + 1; loc <= last; loc++)
if( list[loc] < list[minIndex])
//comparison
minIndex = loc;
From first+1 to last is n-1 comparisons, i.e. length-1 comparisons
Remember this function only finds location of min value of the unsorted
list and each time the unsorted list gets 1 less.
So 1st time this function is executed then it makes n-1 comparisons, 2nd
time it makes n-2 comparisons, and so on.
Hence the number key comparison:
Also, the function is executed same amount of times as swap
function since it is in the same for loop as seen. Thus
function is executed n-1 times
insertion sort: array based lists
Less comparisons than selection sort.
Insertion sort sorts the list by moving each element to its proper
place.
E.G.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Note: From index 0 to 3 the list is sorted. So we start @ position 4, i..e
unsorted part of the list.
We need to move list[4] to its correct place, i.e. to list[2], see b.
To do this you copy list[4] (element you want to move) into temp, seen in
c.
Then you move all the element from where you want to insert (position
2) until the position of the one you want to copy -1 (position 4-1) 1
onwards as seen in d. You start copying from the highest index (copy 3
to 4). After copying it looks like e.
Then lastly insert temp
We divide lists into two sub lists, upper (sorted) and lower
(unsorted).
We move elements in lower sub list to the upper sub list in their
proper places.
We use index firstoutOfOrder to point to 1st element in the lower
sub list, i.e. the unsorted sub list. Initially it is initialized to 1.
The pseudo code:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
note: Initially the whole unsorted list start @ second location, thus we
initialize it to 1.
If statement: if 1st element of lower sub list (unsorted) is smaller than
element before 1st element of lower sub list Then DO
copy 1st element ( element we want to move into correct position) into
temp
set loc to firstOutOfOrder
Starting @ location = firstOutOrder – 1, i.e. position we are going to
move all the elements down, so list[loc] = list[loc-1] and then we
decrement loc. We stop when element in upper list > than the temp
Explanation of this code:
length = 8 and initialize firstOutOrder to 1.
list[firstOutOrder] = 7, list[firstOutOrder -1] = 13, 7 < 13. Thus the if will
be true.
temp = list[firstOutOrder] = 7
location = firstOutOrder = 1
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
In the do-while:
list[1] = list[0] move element one down
location = 0 (decrement location)
The code:
template <class elemType>
void arrayListType<elemType>::insertionSort()
{
//firstOutOfOrder will point to 1st element in lower sub list.
int firstOutOfOrder, location;
elemType temp;
//variable to store firsOutOrder, i.e. 1st element in
lower sub list
//for loop: for each 1st index of lower sub list we need to insert it
for (firstOutOfOrder = 1; firstOutOfOrder < length; firstOutOfOrder++)
//if 1st element of lower sub list is less than element before it
if (list[firstOutOfOrder] < list[firstOutOfOrder - 1])
{
temp = list[firstOutOfOrder];
//store 1st elemetn in temp
location = firstOutOfOrder;
//set location to 1st
element
do
//after the do_while loop location will be
position where 1st element need to be stored in the list
{
//starting @ element before firsOutOrder and ending @
where it must be inserted move all the element one onwards
list[location] = list[location - 1];
location--; //decrement location
}
while (location > 0 && list[location - 1] > temp);
//terminates when element @ (location - 1) is smaller than
//temp. This means that temp needs to go in location
//also terminates when location is bigger than 1
list[location] = temp;
//set 1st element in the
correct location
}
} //end insertionSort
See if you can follow this code with this example:
o firstOutOrder is position 4.
o in the if, 12 < 15, this if statement is true
o Set location to 4 location = firstOutOfOrder; and store 12 in temp
o Now move each element starting from location-1 one down, until list[location1] < temp. ‘list[location-1] < temp’ means that the element(temp) needs ti be
inserted @ location.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
insertion sort: linked list-based lists:
In linked lists we can only traverse the list in one way compared to
array.
Suppose firstOutOrder is a pointer to the node that is to be moved
to its proper location and lastInOrder is a pointer the last node of
the sorted portion of the list.
1st we compare the info in firstOutOrder with info in the 1st node
(8), if the info in firstOutOrder is < than info in 1st node, then the
node firstOutOrder is moved before the 1st node,
Otherwise we search the list starting at the 2nd node to find the
location where to move firstOutOrder.
As usual we search the list using two pointers, trailCurrent and
current
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Also we handle special cases such as an empty list, a list with one
node, or list which node firstOutOfOrder is already in the proper
place.
The pseudo code:
Note: In the while loop: while current’s info is smaller than
firstOutOfOrder advance both the pointers. If it’s not true that
current’s info is smaller than firstOutofOrder than we found position
where firstOutOfOrder must go. Then we must enter firstOutOfOrder
between trailCurrent and current.
The last else accounts for if current is equal to firstOutOfOrder and it
means firstOutOfOrder is actually at the right place and don’t need to
be moved. Now we need to move the unordered list on so
lastInOrder = lastInOrder->link; moves lastInOrder onwards and
lastInOrder donates last part of ordered list
lastInOrder->link = firstOutOfOrder->link;
//let node that
lastInOrder is pointing to point to node after firstInOrder,
i.e. bypass firstOutOfOrder
firstOutOfOrder->link = current;
//let firstOutOfOrder node
point to current’s node
trailCurrent->link = firstOutOfOrder;
//let trailCurretn’s
node point to firstOutoforder’s node, so basically now we
adding firstOutOfOrde inbetween current and trailcurrent.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
A visual example:
Case 2, i.e. if current will be equal to firstOutOforder and last else will
get executed:
Suppose:
firstOutOforder is not < than 1st element thus we use trailCurrent and
Current to search the list while current < firstOutOforder, or until current
> or = to firstOutOforder:
Because current = firstOutOforder so firstOutOforder is in right place and
we don’t move it. But we do move lastInOrder on because the ordered
list needs to move onwards.
The code for this function ( This code will be in the program):
template <class elemType>
void unorderedLinkedList<elemType>::linkedInsertionSort()
{
//create all the pointers that we need
nodeType<elemType> *lastInOrder;
nodeType<elemType> *firstOutOfOrder;
nodeType<elemType> *current;
nodeType<elemType> *trailCurrent;
lastInOrder = first;
//we start with the ordered part being only the
1st element
//because 1 element is ordered, so set lastinOrder to point to 1st element
if (first == NULL) //list is empty
cerr << "Cannot sort an empty list." << endl;
else if (first->link == NULL)
//list is of lenght 1, i.e. first node's
link point to NULL
cout << "The list is of length 1. "
<< "It is already in order." << endl;
else //else list is not length 1 and not empty
while (lastInOrder->link != NULL)
//while lastInOrder is not @
end of list
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
//remember lastInOrder is sorted portion of list so if its @
end then the whole
//lsit is empty
{
firstOutOfOrder = lastInOrder->link;
//set firstOutOforder
to point to node after
//lastInOrder
if (firstOutOfOrder->info < first->info)
//if
firstOutOfOrder < 1st element
//then move firstOutOfOrder to front
{
lastInOrder->link = firstOutOfOrder->link;
//point
lastInOrder node to ndoe
//after firstInOrder
firstOutOfOrder->link = first;
//let firstOutOfOrder
point to 1st element
first = firstOutOfOrder; //let first point to
firstOutOfOrder
}
else //else we search the list until we find a place for
firstOutOfOrder
{
trailCurrent = first;
//trailcurretn point to 1st
node
current = first->link;
//urrent point to 2nd node
//while current's info < firstOutOfOrder's info we move
current and
//trailcurrent on. Here we stop when current = or >
firstOutOfOrder
//since we gona insert firstOutOfOrder between current
and trailCurrent
while (current->info < firstOutOfOrder->info)
{
trailCurrent = current;
current = current->link;
}
if (current != firstOutOfOrder) //if current not =
firstOutOfOrder
//then insert firstOutOfOrder between current and
trailCurrent
{
lastInOrder->link = firstOutOfOrder->link;
firstOutOfOrder->link = current;
trailCurrent->link = firstOutOfOrder;
}
else //else they equal so don't move firstOutOfOrder,
but move
//lastInorder onwards, because ordered part of
list needs to move on
lastInOrder = lastInOrder->link;
}
} //end while
} //end linkedInsertionSort
Analysis: insertion sort:
Suppose list is of length n. Just learn the table
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Shellsort
This is modified version of insertion sort to reduce number of item
movements.
Also called diminishing-increment sort
In this sort the elements of the lists are viewed as sublists at a
particular distance.
Each sub list is sorted, so that elements that are far apart move
closer to their position.
Example:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Here we have a list of 15 elements. Let’s view the list as 7 sub
lists, i.e. we sort the elements at a distance of 7. So in general the
amount of sub lists give us the distance.
By distance we mean element in sub lists are 7 spaces from each
other. Notice element 10 and 60 are 7 index apart.
Then we sort each sub list individually, look @ image on the top
right. Note some of the elements, 2, 19 and 60 are closer to their
final sorted position. The list is then stored
In next iteration, image b, we sort the in the previous stored list,
list on top right, with distance of 4.
Finally with the next iteration we take previous list and sort it with
length of 1. This is the final sorting phase and TA-DA.
So we sorted the elements of distance 7, 4 and 1. The sequence
1,4 and 7 is called the incremental sequence.
How do we chose incremental sequence? We use this sequence
because it is Le Best. Sequence: 1, 4, 13, 40, 121, …. Sequence
formulae: 3*increment+1
The code:
template <class elemType>
void arrayListType<elemType>::shellSort()
{
int inc;
//increment will get the sequence 1,4,13,40... the increment sequence
//we use for which distance we sort the elements with each increment
for (inc = 1; inc < (length - 1) / 9; inc = 3 * inc + 1);
do
{
//this inner for loop runs as many times as the distances chosen by the outer for
//loop. e.g. if length is small then only distance of 1 will be chosen if length
//about 25 then distance will be 4 and then 1
for (int begin = 0; begin < inc; begin++)
intervalInsertionSort(begin, inc);
//this function sorts
the sub lists each time
inc = inc / 3;
}
while (inc > 0);
} //end shellSort
Note: we use the function intervalInsertionSort which is a modified
version of insertion sort we used previously for arrays. This function
sorts each sub list, so it only need to sort the elements of inc
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
distance apart from each other. It also starts @ begin. This is
exercise so ya.
Analysis of shell sort:
Estimated @
Lower bound on comparison-based sort
algorithms
We are going to discuss the best case scenarios for the selection
and insertion sort (comparison based) algorithms.
We can trace the execution of a comparison based algorithm
using a graph called a comparison tree.
Let L be a list of n distinct elements, where n>0. For any j and k
where j ≥ 1, k < n (j and k are index between 1 and n-1), either L[j]
< L[k] or L[j] > L[k]. ‘L[j] < L[k] or L[j] > L[k]’ this is the comparisons
we make.
The tree is binary because comparison of the keys has 2
outcomes.
We draw a comparison as a circle which represents a node. Inside
the node we wrote j:k representing the comparison L[j] with L[k].
If L[j] < L[k] we follow left branch, otherwise we follow the right.
The leaf is a rectangle which represents the outcome and final
nodes.
E.g.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Top node is called the root node. Straight line that connects the
node is called the branch.
Sequence of branches from a node, x, to another node, y, is called
a path.
Associated with each path from root( top node) to leaf (outcome)
is a unique permuation of the elements L. For a list size of n
elemetns there are n! permutations. Thus, a comparison tree of
with n will have n! leaves.
Now do comparison based sorting algorithms. This is only for the comparisons:
Theorem: Let L be a list of n distinct elements. Any sorting algorithm that sorts
L by comparison of the keys only, in its worst case, makes at least O(nlog2n)
key comparisons
Quicksort: array-based lists:
o Uses the divide and conquer technique.
o List is partitioned into two sub lists and the two sub lists are then
combined in such a way that the end list is sorted.
o In quicksort the sorting work is done during the partitioning of the
list
o Algorithm:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
o We use quicksort to sort the sub lists which is recursion to solve
the sub lists.
o To partition the list into two sub lists, lowerSublist and
upperSublist, we choose an element called a pivot.
o Elements in the lowerSublist are smaller than the pivot and
elements in the upperSublist are bigger then the pivot.
o E.g.
consider
We chose pivot in the hope that length of both sub lists are nearly equal
Lets chose 50 as pivot:
Inthis picture we have already portioned the list, i.e. move all elements
smaller than pivot to the lowerSublist and all elements > pivot to the
upperSublist
o The partition algorithm is as follows:
o Example:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
We chose pivot to be middle, i,e. @ position 6
Then swap the pivot with 1st element
Explanation of step 1 in the algorithm:
Determines the pivot and moves the pivot in the 1st array position.
smallIndex is a variable that points to last element in the lower sub list,
i.e. element smaller than pivot
The variable index point to the 1st element in the sub lists that need to be
sorted
The picture of this:
Explanation of step 2 in the algorithm:
Step 2 is computed in a for loop
So if the element @ current index is smaller than the pivot then we
advance smallIndex ( i.e. make space to move element @ index in the
lower Sub list) to next array position and swap elements @ index and
smallIndex
Consider we have this:
Then suppose after executing step 2 we get:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
So now, list[index] < pivot, thus 1st move smallIndex 1 onwards and then
swap list[smallIndex] with list[index].
After the move we get:
Notice index has been moved on and also the upper sub list has moved
on
Now the next iteration we compute step 2 again:
list[index] > pivot, this move list[index] to upperSublist. This is
accomplished by leaving index @ it’s position, but increasing the size of
upperSublist by one.
After completing step 2 until all the elements are moved we get:
Step 3:
We move pivot inbetween lowerSublist and upperSublist. We do this by
swapping pivot (1st index) by smallIndex.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
upperSublist is between the two indices smallIndex and index.
o The code of the partition algorithm. This only partitions the lists, it
doesn’t sort the sublists yet
template <class elemType>
int arrayListType<elemType>::partition(int first, int last)
{
//remember first is index of 1st element
//last is index of last element
elemType pivot;
//create variable to store pivot
int index, smallIndex;
//create index we use in the partioning
//smallIndex points to last element of lowerSublist and index
//point to 1st element in list containing elements that need to be moved
swap(first, (first + last) / 2); //swap first element with the
middle(pivot) element
pivot = list[first];
//set pivot to hold 1st element
smallIndex = first;
//let smallIndex point to first element
//so now the lowerSublist only consist of the 1st element
//1st we let index point to 2nd element and go through the whole
//list(i.e. until last)
for (index = first + 1; index <= last; index++)
if (list[index] < pivot) //we will move element @ index each time
to the back of lowerSublist if the element @ index < pivot
{
smallIndex++; //1st we move smallIndex onwards to increase size
//of lowerSublist, i.e. we make space for the element
swap(smallIndex, index); //swap elements @ smallIndex and
index with each other
}
swap(first, smallIndex); //then put pivot (which is @ first) in the middle
//( middle will be given by smallIndex )
return smallIndex; //it returns position @ smallIndex, which is the pivot
}
*****************************************************************
*****************************************************************
My own steps of the partition function:
1: Swap first and middle value
2: Record the first value as pivot
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
3: Let smallIndex point to 1st
4: Let index start @ second element and then each time
if element @ index < pivot
then first move smallIndex onwards (smallIndex++)
and then swap values @ smallIndex and index
Each time move index onwards
5: swap 1st element with element @ smallIndex
6: we return smallindex which will be the pivot returned
Then we apply this partition procedure to the left side of the pivot and
then to the right side of the partition. e.g.
*****************************************************************
*****************************************************************
o We already have given the swap function but here it is again:
o Now once the list is portioned into lowerSublist and upperSublist
we apply the quicksort method to sort the two sublists.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
o We use recursion to implement the quicksort.
o The partition function return pivot so the indexes of where the two
sub lists start can be determined.
o Code for the recursion quicksort given the starting and ending
position of the list:
//the function that represents the recursive quick sort algorithm
//this function uses partition to partition the list 1st in the 2
//partitions
template <class elemType>
void arrayListType<elemType>::recQuickSort(int first, int last)
{
int pivotLocation; //pivot location
if (first < last) //if first is smaller than last
//this is the exit case for the recursive function
{
//remember partition function returns pivot location and partitions
//the list
//so how does this work: 1st the list is partioned.
//Then using recursion the sublists lowersublists and
//upperSublists are partioned itself by calling the recursion
//fucntion again giving the lower adn upper limits of the sub lists.
//but each time we decrease the upper and lower limits
//of each lists thus decreasing the length of the sublists.
//recQuickSort(first, pivotLocation - 1); this statement refers
//to the call each time of the lowerSublists, but we make the pivot
//location 1 less each time, thus it partition a smaller part of the
list
//each time with the pivot(being bigger) than the rest being to the
right.
//This actually sorts the list
pivotLocation = partition(first, last);
recQuickSort(first, pivotLocation - 1);
recQuickSort(pivotLocation + 1, last);
}
}
o Then we give the code for the quicksort function that we put
in arrayListType class. this function simply calls the recursive
quick sort function (recQuickSort):
template <class elemType>
void arrayListType<elemType>::quickSort()
{
recQuickSort(0, length -1);
}
Analysis: quicksort
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Mergesort: linked list-based lists
Like quicksort, mergesort also uses divide and conquer technique.
It also partitions the list into two sub lists, sorts the sub lists and
then combines the sorted sub lists into one sorted list.
Mergesort partitions the list in a different way than quick sort.
Mergesort divides the lists into 2 sub lists of nearly equal size.
Then it divides those sub lists into 2 sub lists and continues to
divide each of the sub lists into two sub lists until the sub lists
consist of a single element each. Then it merges the single
element sub lists. Each time it merges the sub lists then the
merged sub lists are ordered.
We do not use a pivot here in mergesort
*****************************************************************
This is what you should look out for in the
exam
E.g.:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
*****************************************************************
How to divide a linked list:
We need to find the middle of the list, to do this we use 2 pointers,
middle and current.
We set middle to 1st node and current to 3rd node. (If list has only 2
nodes then we set current to NULL)
We advance both pointers. Every time we advance middle by one
node, we advance current. If current is NOT NULL, we advance
current again. So for the most part for every time we advance
middle by one, we advance current by two.
Thus when current is Null then middle will point to the last node of
the 1st sub list and we found where to divide the sub lists.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Now we divide the 2 lists: We take the link of middle(i.e. node after
middle we assign the pointer otherHead to the link. Then we set
the link of middle to NULL.
Code for the divideList function:
//class to divide a linked list into two equal sized lists
//the list start @ first1 and end @ first2
template <class Type>
void unorderedLinkedList<Type>::divideList(nodeType<Type>* first1, nodeType<Type>*
&first2)
{
//create the 2 pointers we use to divide the list
nodeType<Type>* middle;
nodeType<Type>* current;
if (first1 == NULL) //list is empty
first2 = NULL;
else if (first1->link == NULL) //list has only one node
//and then we can't divide it any further
first2 = NULL;
else
{
middle = first1;
//we set middle to 1st
current = first1->link;
//we set current to 2nd node
if (current != NULL) //list has more than two nodes
current = current->link; //move current on to the 3rd node
//remember if the list has more than 2 nodes we start by setting
middle to 1st node and current to 3rd node
while (current != NULL)
//while not @ end of list, i.e. current is
!Null
//remember each time we move middle 1 onwards we move current 2
onwards if current is not NULL, i.e. current not @ end
{
middle = middle->link;
//move middle onwards
current = current->link; //move current onwards
if (current != NULL)
//check if current is NULL
current = current->link; //if not Null we move current
on 1 more. Thus now current will move 2 times for every 1 move of middle if
current is not pointing to NULL
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
} //end while
//after this middle will point to last node of 1st sub list
first2 = middle->link; //first2 points to the first
//node of the second sublist
middle->link = NULL; //set the link of the last node
//of the first sublist to NULL, i.e. splitting the 2 nodes
} //end else
} //end divideList
Now merging the lists:
Now the sublists are sorted and the next step is to merge the
sorted sub lists.
Suppose we have this example:
First1 point to 1st node of 1 sub lists and first2 points to 1st node of
other sub list
We 1st compare the info of the 1st node of each of the 2 sub lists to
determine the first node of the merged list
So we create 2 pointers, newHead and lastMerged. newHead
points to head of the merged list (joined sub list) and lastMerged
points to last node in the merged list.
1st we compare the 1st nodes of each of the sub lists. Then we let
newHead point to the node containing the smallest element. After
we compare the 2 sub lists we set chose the node which was the
smallest and let lastMerged point to it. So basically we added the
node to the merged list by doing this. We also move first pointer on
depending of which sub list’s node was added to the merged list.
In the picture first1 points to the 1st node in sub list 1.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Again we repeat the process of comparing. Compare first1 with
first2. first2 contain smaller element thus add node to merged list
(by pointing lastMerged to the node) and move first2 on:
Then we continue this process until either first1 or first 2 is NULL.
If first1 is NULL the 1st sub list is exhausted 1st and we attach rest
of remaining nodes of second sub list at the end of the merged list.
Otherwise we sub list 2 is exhausted 1st and we attach rest of sub
list 1 to the merged list.
The mergeList function:
F
template <class Type>nodeType<Type>* unorderedLinkedList<Type>::
mergeList(nodeType<Type>* first1,nodeType<Type>* first2)
{
//first1 point to 1st node of first sub list
//first2 point to 1st node of 2nd sub list
nodeType<Type> *lastSmall; //pointer to the last node of
//the merged list
nodeType<Type> *newHead; //pointer to the merged list
if (first1 == NULL) //the first sublist is empty
return first2;
else if (first2 == NULL) //the second sublist is empty
return first1;
else
{
//neither sublsit is empty
if (first1->info < first2->info) //compare the first nodes
//if 1st list's 1st element < 2nd list's 1st element
//then the merged list(i.e. newHead) will start @ the
//first list
{
//now we will
newHead = first1; //let newHead point to 1st list's 1st
element
first1 = first1->link;
//move pointer first1 1 onwards
lastSmall = newHead;
//let lastSmall point to newHead,
i.e. 1st element on merged list
}
else //else merged list start @ 2nd sub list
{
newHead = first2;
first2 = first2->link;
lastSmall = newHead;
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
}
//while neither first1 or first2 is not NULL
while (first1 != NULL && first2 != NULL)
{
if (first1->info < first2->info) //compare the 2 sublists's
1st element
{
//if 1st sub list contained the smaller element we will
move the element to the merged list
lastSmall->link = first1; //let lastSmall's node(last
node in merged list) point to 1st list's 1st element. In doing this you will link
up the merged list with 1st list's 1st node. Thus adding the node to the merged
list
lastSmall = lastSmall->link;
//let lastSmall point
to 2nd node of first sub list
first1 = first1->link;
//move first1 1 onward
}
else
{
//else we add 2nd sub list;s 1st element to merged list
lastSmall->link = first2;
lastSmall = lastSmall->link;
first2 = first2->link;
}
} //end while
//now we need to check which pointer(first1 or first2) was NULL 1st.
If either one is NULL 1st then that list was all added to merged list and we need
to add the rest of the other list to the merged list
if (first1 == NULL) //first sublist is exhausted first( i.e. all
added to merged list)
lastSmall->link = first2; //connect rest of list 2 to the
merged list, we do this by linking last node of merged list(lastSmall) to 1st node
of list 2(first2)
else //second sublist is exhausted first
lastSmall->link = first1;
return newHead;
}
}//end mergeList
Finally we write the recursive mergesort function, recMergeSort. It
is almost the same as recQuickSort function.
//implements the mergesort algorithm using recursion. I uses the function
divideList
//and mergeList. We pass the first node as reference to this function
//We what we do in this function's 2nd if:
//1) use divideList function with the head and otherHead pointers
//2) call the function recursively twice once with each pointer to each sub list
//3) call mergeList with head and otherHead pointers and give it the value to head
template <class Type>
void unorderedLinkedList<Type>::recMergeSort(nodeType<Type>* &head)
{
nodeType<Type> *otherHead; //this will point to the 2nd sublist each time a
list is divided. remember head will point to 1st sublist each time list is
if (head != NULL) //if the list is not empty
if (head->link != NULL) //if the list has more than one node
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
{
divideList(head, otherHead);
//devide the current list
into two sub lists
recMergeSort(head);
//this will call the function again
with the first sub list and then devide it again into two sub, then again function
will get called and the sublist will be devided into two sub lists, until node
lenght in the sub lists are 1
recMergeSort(otherHead); //this will divide all the second
sub lists until all of them have lenght of 1
head = mergeList(head, otherHead);
//then this will merge
all the lists. Everytime two lists are merged the lists are sorted in each merged
list. remember mergeList returns the pointer to the newly merged list each time
}
} //end recMergeSort
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Finally we write the definition of the mergeSort function. The
function that will use recMergeSort in order to sort the list. You will
call mergeSort in main to sort a certain list object.
template<class Type>
void unorderedLinkedList<Type>::mergeSort()
{
recMergeSort(first);
//mergeSort the list
//remember first point to calling object's list. need
//to give if pointer to the first element of the lsit
if (first == NULL) //if list is empty
last = NULL; //set last to NULL
else //else list is non empty then set last to the last node
{
last = first; //set last to point to 1st node
while (last->link != NULL) //while not @ last node
last = last->link; //move last 1 onwards
}
} //end mergeSort
We include this function in the class unorderedLinkedList. The
functions divideList, merge, recMergeSort can all be include in the
private access specifier of this class since these functions won’t be
called in main, but will be used by the private member functions
(the function mergeSort) of the class.
Analysis: mergesort
Maximum Number of comparisons of mergeSort:
Not going to go into detail. If it is in exams then study it. P566
Heapsort: array-based lists
o WE typically view data in the form of a binary tree.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
o Note in this sort each node has two child nodes. If the parent node
is @ index position k, then the child nodes are @ position 2k+1
and 2k+2.
o E.g.: Let’s look @ 80. It is @ position (index) 2. So k is 2. So using
the formulae 2k+1 and 2k+2 with k being 2 we get position 5 and
6. Thus nodes @ those positions (2 and 5) are 80’s child nodes.
Look 75 and 30 are the child nodes of 80.
o Top node is called root node. 70 is called the left child or the root
and 80 is called the right child.
o In general for node k (which is in position k-1), its left child is @
position 2k -1 and the right child is @ 2k+. From left child to right
child we add 2. (THIS IS JUST HOW IT WORKS< STILL
CONFIRM WHY)
o The bottom nodes are called leaves.
Build Heap:
1st step in this algorithm is to convert list in to a heap, called a
buildHeap
The algorithm is as follows:
Suppose list of size length.
let index = length / 2 -1 (basically the middle of the list) . list[index]
is the last element in the list which is not a leaf. This element has
at least one child.
Thus list[index+1] …. list[length-1] are leaves
First we take a part of the tree called a subtree with list[index] as
our root node. Note this subtree @ most has 3 nodes. We then
convert the subtree with the root node list[index-1] into a heap and
so on.
To convert a subtree into a heap:
Suppose that list[a] is the root node of the subtree, list[b] is left
child, and list[c] if it exist, is the right child. We compare the childs
with each other to determine the larger child. Suppose largerIndex
indicates the larger child.
Compare root (list[a]) with list[largerIndex] (largest child). If list[a] <
list[largerIndex] then swap list[a] with list[largerIndex] (swap largest
child with root node), otherwise, the subtree with root node list[a] is
already in a heap.
Suppose after this swap the subtree with root node list[largerIndex[
might not be in a heap. If this is the case, then we repeat Steps 1
and 2 at the subtree with root node list[largerIndex] and continue
this process until either the heap in the subtrees is restored or we
arrive at an empty subtree
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Heap sort explanation:
These pictures are in the folder to better view them
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Okay in the explanation is wrong because after applying the
headsort then lsit will be in descending order. We want it in
ascending order. So to fix instead of step 1 we swap last and 1st
element. Root will now be smallest element and last element will be
biggest element. So then we store the root
The algorithm for Heapsort
1. Heapify
2. Root will now be biggest element. Swap root and last node. Then
store root in array which will be the smallest element.
3. Replace the first position with the last element
4. Check if the tree is Heap (either Min or Max heap)
If Yes then go to 2
If no then go to 1
Now for the code:
low contains index of the root node of the subtree and high contain the
index of the last item in the array or list.
//this function start with the subtree being the top(depending what you give the
value low), i.e. parent of subtree
//is root node. Then it works it's way down the subtrees
//this function heapify the list, i.e. checks each sublist and replaces
//parent with biggest child if the biggest child is bigger than parent
//low point to parent node of subtree and high point to
//last item in the list( or tree)
//after this function executes then the tree will be in Max heap form
template<class elemType>
void arrayListType<elemType>::heapify(int low, int high)
{
int largeIndex;
//variable to store index of largest child
elemType temp = list[low]; //copy the root node of the subtree
largeIndex = 2 * low + 1; //set largeIndex to be index of left child
//remember left child is @ index 2k+1 if parent @ k
while (largeIndex <= high) //while lageIndex <= last el
{
if (largeIndex < high)
//if largeIndex not @ end
if (list[largeIndex] < list[largeIndex + 1]) //if left child
< right child
largeIndex = largeIndex + 1; //then let largeIndex
point to right child
//this will ensure largeIndex points to largest child
if (temp > list[largeIndex]) //subtree is already in a heap
//temp is parent of subtree, so if this true then we dont have
to swap
//parent with largest child
break; //then exit the if else statement and continue on to
while
else
//else we need to swap largest child with parent
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
{
list[low] = list[largeIndex]; //move the larger child to be
parent
//'s position. So replace element that was @ parent with
largest child
//this part creates the new subtree(i.e. moves subtree down)
//-------------------low = largeIndex; //This moves low down so that we can start
with a new
//subtree which is below the subtree we worked in
largeIndex = 2 * low + 1; //this moves largeIndex to be left
child of
//the new subtree
//--------------}
}//end while
list[low] = temp; //insert temp into the tree, that is, list
} //end heapify
Next we use heapify function in the function buildHeap to convert a list
into a heap. i.e. we build a Max Heap using the heapify function.
Notice in the previous explanation (in the pictures) we started with 1st
element, but here we start in with the middle element being the root
node.
The buildHeap function:
//this function builds a Max Heap using the heapify function.
//we start building the heap with the middle element(donated by length/2-1)
//and end @ the last index
template <class elemType>
void arrayListType<elemType>::buildHeap()
{
//starting @ middle element being the root node build the heaps
for (int index = length / 2 - 1; index >= 0; index--)
heapify(index, length - 1);
//build the Max Heap
}
The heapsort function uses buildHeap() function once and uses
heapify function in a for loop
template <class elemType>
void arrayListType<elemType>::heapSort()
{
elemType temp;
//variable to hold the root element each time
buildHeap(); //build the 1st heap
//lastOutOfOrder stores the last element each time of the heap
for (int lastOutOfOrder = length - 1; lastOutOfOrder >= 0;lastOutOfOrder--)
{
temp = list[lastOutOfOrder];
//store the last element in temp
//----swap root ndoe and lst node
list[lastOutOfOrder] = list[0]; //store the root node in the last
position
list[0] = temp;
//let root node get last element
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
//------heapify(0, lastOutOfOrder - 1);
//remember heapify puts the tree in Max heap form, i.e. all parent >
their childs
//we call heapify with 0. 0 will become 'low' in heapify which is
parent
//of the subtree. so 1st element will be parent of 1st subtree
}//end for
}//end heapSort
Analysis: heapsort:
On average, the number of comparisons made by heapsort is
n is the amount of elements.
Binary trees and b-trees
Intro
When data is being organize, a programmer’s highest priority is to organize it in such
a way that insertion, deletion, and lookups are fast. To organize data in array has
limitations since insertion and deletion is time consuming since it requires data to be
moved. Item insertion and deletion is easier in linked list, because we don’t move the
data. However drawback of linked list is they must be processed sequentially.
Binary trees
Organizes data dynamically so that insertion, deletion and lookups
are more efficient
Def:
Already discussed in Heapsort.
A picture:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
A is called parent of B and C. B is left child of A and C is right child
of A. Notice children connected to their parent by an arrow from
parent to the child.
Arrow is called a directed edge or a directed branch. or simple
branch
When parent has no left or right child then we end it with three
lines as seen in picture, e.g. C has no left child.
Note that B itself can also be seen a binary tree with B being the
root node of the binary tree denoted 𝐿𝐴 . B is root node of 𝐿𝐴
Is node B. 𝐿𝐴 and 𝑅𝐴 are also binary trees.
Remember 𝐿𝐴 stands for left subtree of A, its root is B
Every node at most has 2 children. Thus every node, other than
storing its own info, must keep track of its left and right subtree.
Thus every node has 2 pointers, llink and rlink. llink point to root
node of the left subtree (left child) and the rlink to the right child.
Following code defines a struct node for a binary tree:
template <class elemType>
struct binaryTreeNode
{
elemType info;
binaryTreeNode<elemType> *llink;
binaryTreeNode<elemType> *rlink;
};
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
o A pointer, root, points to the root node of the binary tree.
o Node is called leaf if it has no children.
o There is a unique path from the root to every node in the binary tree.
o Level of a node: is the number of brances (arrows) on the path from the root
to the node. E.g. A is level 0; B & C is level 1; D, E & F is level 2
o Height of a binary tree is the number of nodes on the longest path from the
root to a leaf. Basically from top to most bottom node. Count how many levels
there are
IMPORTANT:
A binary tree is a recursive object since a subtree itself is a binary tree
but with the root node being moved onwards.
Recall 1st node is root node. Then its left child node is the left subtree
and right child node if the right child node. Now these subtrees are
binary trees themselves with the top of the binary tree being the root
nodes.
An image to explain:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
You see the left subtree of the orange binary tree is itself the red binary
tree.
So red binary tree: root->llink. This pointer point to the root node of red,
i.e. root node of the red binary tree. Then if we move on again to the
next subtree( i.e. reds left subtree) then we get the pointer
root->llink->llink. This is root node of purple tree which itself is a tree.
Notice when we advance we add ->llink or ->rlink to advance to the right
side
So to write recursive function using the binary tree we will call the
function with the argument/s of pointerName->llink or/and
pointerName->rlink. Note pointerName is normally the root pointer of the
whole binary tree.
Height function:
We let pointer p point to the root node.
The procedure for this function:
1. First we find the height of both the left and right subtrees.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
2. Then we find the max( we use the function max) of the two
subtrees. Then we add 1 to it and it will give us the height of the
binary tree.
This procedure is given as this 1 + max(height(p->llink), height(p->rlink));
Because each subtree is a binary tree itself we can apply this procedure
recursively to find the height of each subtree(binary tree). Each time we
call the function recursively, then we go down a level so we call it with
the node’s llink and rlink.
template <class elemType>
int height(binaryTreeNode<elemType> *p) const
{
if (p == NULL)
//end case for recursive function
//if p points to NULL it mean we have reched the end
return 0;
else
return 1 + max(height(p->llink), height(p->rlink));
//’1 + max(height(p->llink), height(p->rlink))’ is the process of
calculating height of a binary tree. Since each left subtree and right subtree is
a binary tree itself we can call this recursively each time calling the function
with the left and right subtree value. p->llink is left subtree and p->rlink is
the right subtree of each binary tree.
}
Binary tree traversal
We need to traverse (visit each node) through a binary tree for
insertion, deletion and lookup operations.
We start @ root node.
For each node we have 2 choices:
These choices leads the three different traversal methods of a
binary tree:
o Inorder Traversal:
Called the inorder sequence
o Preorder Traversal:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Called the preorder sequence
o Postorder Traversal:
Called the postorder sequence
These are all recursive traversals since a subtree is a binary tree
itself, but just moved onwards.
Example of inorder traversal:
For simplicity we assume visiting a node means outputting data
stored in the node.
We start traversal @ node A. We have pointer root that point to A.
So the steps are:
Now we cannot do step 2 until we have finished Step 1:
As before we can’t go to step 1.2 before we do step 1.1:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Step 1.3:
So always we apply the 3 steps each time we go down a node
When a subtree is empty then the step will automatically be
completed.
So now we must go waay back to the start. Step 1 is completed
and now we must do step 2:
Step 3:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Now step 3 is complete thus the whole traversal of the binary tree
is complete.
The output: B D A C
Now the other traversing is basically the same except the order of
the steps.
So with the inorder after visiting the left subtree of a node we must
come back to the node itself, but this is a problem since we can
only go down we can’t go up since pointers are only going down.
To solve before going to a child, we save a pointer to the parent
node. A way to do this is to write a recursive inorder function
because in a recursive call after completing a particular call, the
control goes back to the caller, i.e. we go back to the parent.
The code to this is in the program binary tree.
Study the program binary tree
Binary search trees
This is a special type of binary tree
This allows us to search for items for efficiently.
Def:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Picture:
Note:
This makes it easier to search for an item. Suppose we want to
search for 58. Then start with root node. 58 ≠ 60 and 58 < 60.
Since left subtree’s root (in this case 50) < root node we know 58
will be in left subtree and not in right subtree. We can continue with
this procedure until we find the value.
Operations on a binary search tree:
Every binary search tree is a binary tree, thus operations to find
number of nodes, number of leaves, and to do inorder, preorder,
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
and postorder traversals are the same. Thus we can inherit from
binaryTreeType class in file “binaryTree.h”
Look @ the program binarySearchTree
The only new functions in the class bSearchTreeType is:
o search
o insert
o deleteNode
o deleteFromTree(private)
Here are the 4 cases for the deleteNode method with this example:
The 4 cases:
case1: Want to delete node 45. The node to be deleted is a leaf so we
determine if it is a left or right child of previous node, then set either llink
or rlink of the parent node to NULL and deallocate the memory occupied
by this node. After deletion tree a shows resulting tree
case2: Want to delete 30. Left subtree of the node we want to delete is
empty right one is not. We make the llink of parent node of node we
want to delete(50) point to right child of the node we want to delete.
Thus we connect the bottom part of the tree after the node we want to
delete to the upper part of the tree. b shows resulting tree
case3: Same as case 2 except here right subtree is empty. So we make
rlink of the parent node of the node you want to delete and let it point to
the left child of the node you want to delete. c shows resulting tree
Note: For case 2 and case 3 we point llink to right and rllink to left. Its
opposites.
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
case4: Suppose you want to delete 50. Node has two non-empty
subtrees. We reduce this case to either Case 2, or Case 3. 1st we go to
the left subtree (30). Then we continue searching downwards until we
get to a node whose right subtree is empty. We arrive @ 48. Next we
swap data in node to be deleted with this node that we found. Then we
apply case 3 to the node we arrived @ (which is 50 now) which will
delete the node. d shows resulting tree
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Case 4 is complicated so look @ this picture when reading the code of
case 4: This explains the 2 subcases in case 4, i.e case when current
hasn’t moved(then trailCurrent will be NULL because we declared it like
this when we started) or case when current has moved.
Binary search tree: analysis
Giving no explanation just answers. n is size of max
nodes
In worst case(tree is actually linear):
-Successful case: On average it makes (n+1) /2
comparisons.
- Unsuccessful case: makes n comparisons.
Average number of nodes visited in a search is:
Number of key comparisons:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Non recursive binary tree traversal
Quickly going to go over it.
Possible for inorder, preorder and postorder traversals to be nonrecursive.
Look @ program nonRecursiveTraversal
Explanation of the nonRecursiveInTraversal function:
Explanation of the if in the while loop.
One execution of the else statement:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Another execution of the else:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Now the else will stop since current is not NULL and we will continue in
the ‘if’ again.
AVL (height-balanced tree) Trees
A special binary tree that focuses on having a small height in order
to achieve a more efficiently search.
In this tree the binary search algorithm is nearly balanced
Def of perfectly balanced:
A picture of perfectly balanced:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Height of left subtree = height of right subtree
If T is a perfectly balanced binary tree of height h, then the number
of nodes in T is
. If number of nodes in a binary tree is not
then it is impossible to construct a perfectly balanced binary
tree.
Def of AVL binary tree:
So height of left and right subtree differ by 1, so it’s only allowed to
differ by 1 level. Not differ by 1 node
E.g.:
More definitions:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
So left high means left subtree is 1 higher than right
Right high means right subtree’s height is 1 more then left subtree
Equal high means left and right subtree heights are equal.
Basically balance factor is height difference between right and left
subtree
Balance factor(bf) of node x is height of right subtree( of node x)
minus height of left subtree
Bg = height(rsubtree) - height(lsubtree)
Note: balance factor can only be -1, 0 or 1 for a AVL tree since
the height difference between the left and right subtree of an AVL
tree can only be 1
Definition of an AVL node:
This definition is same as normal binary tree except it has balance
factor (bfactor)
Note: A lot of functions are the same of AVL trees as they are for
binary trees. However here are the functions that are not the
same:
o Insertion
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
o deletion
Graphs
Graph representation
Represent pair-wise relationship between a set of objects
Not to be confused with graphs we learned in maths class
Components of a graph:
-Vertex (also called node)
-Edges (arc)
Edges determine relationship between pair of vertices
Graph with 2 vertices and an edge between them
We divide graphs into 2 categories:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Note: In directed graph the order matters.
Relationship of the un-directed graph holds in both directions
2 ways to represent a graph data structure:
o Adjacency Matrix:
The 0-1 means there are either 0 or 1 values in the matrix.
V refers to number of Vertex a graph have
So if we have 1 @ the ith row and jth column then there is an
edge between 0 and 1.
Undirected graph example:
Note: Lines(edges) shows which vertices are connected. E.g.
vertex 1 and 3 are connected.
So in matrix There is 1 @ row 4 and column 1. Thus this
means vertices 4 and 3 are connected and it is because
there is an edge between them
Pros:
-Easy to implement
-Removing an edge take O(1) time
Cons:
-Requires more space
-Adding a vertex takes O(V^2) time
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Directed graph example
We write a 1 @ the row and the column if there is an edge
going from the row’s vertex to the column’s vertex
Note that edge is going from 0 vertex to vertex 3. So there
must be 1 in row 0 and column 3
So row is origin vertex and column is destination vertex
(where arrow is pointing towards)
o Adjacency List:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
Example:
It’s an ARRAY OF VERTICES, which is represented in the
form of ARRAY OF LINKED LISTS. There are 5 vertices so
size of array is 5.
Array index corresponds to vertex number: E.g. linked list in
1st element @ index 0 corresponds to vertex 0 (node with 0).
Each link list’s elements tells you to which that vertex is
linked to, i.e. to which nodes (vertices) the vertex has edges
to.
Example link list @ position 0 corresponds to vertex 0 (@
node 0). The link list has elements 1 and 4. Thus Vertex 0
has edges to vertex 1 and 4.
Pros:
-Saves space
-Adding a vertex is easier
Cons:
-Queries like whether there is an edge from vertex u to
vertex v are not efficient and can be done in O(V) time
Shortest path algorithm:
Edges normally shows a value which is considered the
weight of an edge. The weight of an edge is considered
the cost of the edge. In some application it can be the
time it takes along a route.
Total weight of a path is the sum of the weights
Example:
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
To do the algorithm we make a smallestWeigth array
which holds the smallest weight from the specified
node to each node corresponding to the index
Note: if we pick node 0. From node 0 to node 1 smallest weight will be
16. Smallest weight to 3 will be 2. However we don’t know from node 0
to node 2 since there isn’t an edge connecting them so we say it’s
infinity
We also make a weightfound array and then we say of
we created a smallestWeight array for a specific node
then we set the corresponding index’s element to True.
Then ma BOI we select node closest (with least
weight in smallestWeight, so vertex 3) to Node we
just created the smallestWeight for (node 0) and we
select it. So we select node 3. And thus we set node
3’s weightfound to T:
Also, now we concider nodes 1 and 4 since node 3 has
edges to them. We then consider the paths from 0 to 1
via the node we selected (vertex 3) and from 0 to 4 via
vertex 3 and we can see if we can improve these
paths. So path 0-3-1 weights 14, it’s less than the path
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
0-1 so we update smallestWeight ( in [1] since it
represents smallestWeight from 0 to vertex 1) to 14.
Weight of path 0-3-4 weigths 9 which is more than from
0-4, wo we do not update smallestWeight[4]
Again we select next vertex with smallest weight (after
doing vertex 3)in smallestWeight array that we have
not visited. i.e. we visit node 4. Set [4] to true. Now
consider paths again and make improvements. 4 goes
to 1 and 2 since edges goes to them and they are F in
weighFound table so shortest path from 0 to them have
not been found. Path 0-4-1 weights 13, which is less
than 0-1(in samllestWeight array) so update
smallestWeight with 13 and set [1] to True. Also update
smallestWeight[2] to 7 since 0-4-2 weights that much.
Now again we select the vertex with smallest weight in
smallestWeight that we have not already done, i.e.
which is still False. So we select [2], i.e. vertex 2. Now
set WeightFound[2] to True. So when we start with a
node then set it to True.
df
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Want to earn
R1,135 per month?
Stuvia.com - The study-notes marketplace
In shorter terms:
1) Make 2 arrays, smallestWeight and weightFound
2) Then starting @ vertex 0, set [0] in weightFound array to T and
check the weight from vertex 0 to each other vertex and note it
into the smallestWeight table. If you can’t get the weight note it
as infinity.
3) Each time we go to the next vertex (making the vertex T) that is
false(i.e. haven’t visited) and with smallest weight in
smallestWeight array and we see if we can improve the paths
from vertex 0 to the vertexes that have an edge pointing to them
from the node you visiting. If the paths can be improved then
update smallestWeight array
Downloaded
| vicdp94@gmail.com
Downloaded by:
by: NkuliMckintosh
tyroneissel | isseltyrone@yahoo.com
Distribution of this document is illegal
Powered by TCPDF (www.tcpdf.org)
Want to earn
R1,135 per month?
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )