Data Structures & Algorithms
Data Structures & Algorithms
Higher Nationals in
Computing
Issue 1
Higher National Certificate/Diploma in Computing
Assignment Brief
Student Name/ID
Number
Unit Number and Title 19: Data Structures & Algorithm
Academic Year
Unit Tutor
Assignment Title Data manipulation in different environment
Issue Date
Submission Date
IV Name & Date
Submission Format
The submission of the following forms as a one word processing document :
1. Part 1 : a. A presentation
b. Illustrated document
c. 1000 words report
2. Part 2 : Program source code with relevant screen captures of running program.
3. Part 3 : a. Documentation
b. Program source code with relevant screen captures of running program.
You are required to make use of headings, paragraphs, subsections and illustrations as appropriate,
and theoretical sections can be supported with research and (where appropriate) referenced using the
Harvard referencing system.
HNC/HND Computing 2
Unit Learning Outcomes
LO1. Examine abstract data types, concrete data structures and algorithms. LO2. Specify
abstract data types and algorithms in a formal notation.
LO3. Implement complex data structures and algorithms.
LO4. Assess the effectiveness of data structures and algorithms.
Assignment Brief and Guidance
Part 01:
a. Assume you are a software engineer in a system software development company and the tech lead of
your team asks you to make a 30 minutes presentation for the trainee programmers on the topic of Binary
Search Trees versus other data structures including the speaker notes, when required. (LO1,LO4)
b. Demonstrate the following values in a BST with a simple diagram and write algorithms for inserting
and traversing the tree with step by step illustration.
c. Write a 1000 words report by comparing and contrasting the elementary sorting algorithms with
advanced sorting algorithms. (LO1,LO4)
Part 02:
An Operation theatre needs an application for storing details of patients who undergo operations
daily. Nurses of the wards may insert the patient details such as admission number, name, ward no., age,
type of operation (Heart, Eye, Head ..etc. ),blood pressure , sugar level and so on to the application
and doctors may get the patients to the operation theatre based on the order in which they have been
inserted to the system. Implement the program using a data structure you prefer explaining reasons why
you selected that in your application. You can use any programing language you like. (LO1,LO3)
Part 03:
HNC/HND Computing 3
Acknowledgement
HNC/HND Computing 4
Table of Contents
Part 01:...........................................................................................................................................7
a....................................................................................................................................................7
Presentation for Binary Search Trees versus other data structures.................................7
b.................................................................................................................................................15
Binary Search Tree (BST) Diagram for the given values.................................................15
c..................................................................................................................................................20
Report....................................................................................................................................20
Part 02...........................................................................................................................................24
Source Code..............................................................................................................................24
Implementation........................................................................................................................28
Test Cases..................................................................................................................................30
Error Handling.........................................................................................................................33
Part 03...........................................................................................................................................34
Documentation and Program source code.............................................................................34
1. Create 1000 elements integer array and populate the array with random numbers within the range of
100 to 1000:...........................................................................................................................34
2. Sort the array using insertion sorting technique:..........................................................35
3. Search the array for the values 857, 235, 78, 567, 234, 165, 1020 using binary search algorithm: 35
Execution code......................................................................................................................36
Implementation.....................................................................................................................37
Outcome................................................................................................................................38
References.....................................................................................................................................39
Table of Figures
Figure 1...........................................................................................................................................7
Figure 2...........................................................................................................................................7
Figure 3...........................................................................................................................................8
Figure 4...........................................................................................................................................8
Figure 5...........................................................................................................................................9
HNC/HND Computing 5
Figure 6...........................................................................................................................................9
Figure 7.........................................................................................................................................10
Figure 8.........................................................................................................................................10
Figure 9.........................................................................................................................................11
Figure 10.......................................................................................................................................11
Figure 11.......................................................................................................................................12
Figure 12.......................................................................................................................................12
Figure 13.......................................................................................................................................13
Figure 14.......................................................................................................................................13
Figure 15.......................................................................................................................................14
Figure 16.......................................................................................................................................14
Figure 17.......................................................................................................................................15
Figure 18.......................................................................................................................................18
Figure 19.......................................................................................................................................18
Figure 20.......................................................................................................................................28
Figure 21.......................................................................................................................................29
Figure 22.......................................................................................................................................33
Figure 23.......................................................................................................................................37
Figure 24.......................................................................................................................................38
Table of Tables
Table 1...........................................................................................................................................30
Table 2...........................................................................................................................................30
Table 3...........................................................................................................................................31
Table 4...........................................................................................................................................31
Table 5...........................................................................................................................................32
Table 6...........................................................................................................................................32
Table 7...........................................................................................................................................32
HNC/HND Computing 6
Part 01:
a.
Presentation for Binary Search Trees versus other data structures
Figure 1
Figure 2
Figure 3
Figure 4
Figure 5
Figure 6
Figure 7
Figure 8
Figure 9
Figure 10
Figure 11
Figure 12
Figure 13
Figure 14
Figure 15
Figure 16
b.
Binary Search Tree (BST) Diagram for the given values
Figure 17
Source Code
Algorithm for Insertion
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
return root
# Step-by-step insertion
root = None
values = [12, 34, 23, 56, 34, 78, 45, 78, 23, 78, 89, 4, 57, 3, 8, 9]
Figure 18
Outcome
Figure 19
In-order Traversal Step-by-Step
In-order Traversal Result: [3, 4, 8, 9, 12, 23, 34, 45, 56, 57, 78, 89]
c.
Report
Title:
A Comprehensive Analysis of Elementary and Advanced Sorting Algorithms: Efficiency,
Implementation, and Applicability
Introduction:
Computer science relies heavily on sorting algorithms because they offer a methodical way to
organize data in a meaningful way. The selection of a sorting algorithm is a crucial choice that is
impacted by a number of variables, including effectiveness, simplicity of use, and scenario
adaptability. We compare and contrast the features of basic and sophisticated sorting algorithms
in this report by delving deeply into each one.
Comparison:
Time Complexity:
The time complexity of a sorting algorithm is one of the key performance indicators. The
scalability of elementary sorting algorithms is limited for large datasets because they frequently
display quadratic time complexity (O(n^2)). Advanced algorithms, on the other hand, often reach
O(n log n), demonstrating better performance as dataset sizes rise.
Space Complexity:
Elementary algorithms are memory-efficient because they usually have constant space
complexity. Higher space complexity arises from the need for additional space for recursion or
data structure maintenance in advanced algorithms. When selecting the right algorithm, the
trade-off between memory efficiency and performance becomes critical.
Stability:
For some applications, stability—the maintenance of the relative order of equal elements—is
crucial. The majority of simple sorting algorithms, such as Selection Sort, Bubble, and Insertion,
are stable. On the other hand, some sophisticated algorithms—like Quick Sort—are not
essentially stable. In situations where preserving the original order is necessary, stability
becomes essential.
Ease of Implementation:
Particularly notable for their simplicity and ease of use are elementary sorting algorithms. They
are frequently covered early in computer science education and serve as fundamental ideas.
Because of their complex logic and data structures, advanced algorithms are more difficult for
beginners to understand but beneficial for those who want a thorough understanding of
algorithmic efficiency.
Adaptability:
One important factor to take into account is how well sorting algorithms can be applied to
various scenarios. On datasets that are only partially sorted, elementary algorithms—in
particular, Insertion Sort—can be flexible and effective. Cutting-edge algorithms, like Merge
Sort, perform consistently regardless of the elements' original order. When working with
dynamic datasets or changing data structures, adaptability becomes essential.
Example:
Consider the following graph, where the numbers on the edges represent the distances between
the connected nodes:
A----1----B
| |
3| |2
| |
C----5----D
To find the shortest path from node A to node D using Dijkstra's algorithm:
Set the distance of node A to 0 and all other nodes to infinity.
Select node A and visit its neighbors, updating their distances: B->1, C->3.
Select node B (minimum distance) and visit its neighbor D, updating its distance: D-
>3.
Select node C (minimum distance) and visit its neighbor D, updating its distance: D-
>8.
Select node D (destination node).
The shortest path from A to D is A->B->D with a total distance of 4.
Bellman-Ford Algorithm:
Bellman-Ford algorithm is another algorithm that finds the shortest path between two nodes.
Unlike Dijkstra's algorithm, Bellman-Ford algorithm can handle negative edge weights. The
algorithm works by iteratively relaxing all edges in the graph, reducing the distances to the
destination node until no more improvements can be made.
Example:
Consider the following graph, where the numbers on the edges represent the distances between
the connected nodes.
A----1----B
| |
3| |-2
| |
C----5----D
To find the shortest path from node A to node D using Bellman-Ford algorithm:
Set the distance of node A to 0 and all other nodes to infinity.
Relax all edges in the graph, reducing the distances to the destination node. Repeat this
process for n-1 iterations, where n is the number of nodes in the graph.
After the first iteration, the distances are: B->1, C->3, D->infinity.
After the second iteration, the distances are: B->1, C->3, D->-1.
After the third iteration, the distances are: B->1, C->3, D->-1.
No more improvements can be made, so the algorithm stops.
The shortest path from A to D is A->C->D with a total distance of 2.
Conclusion
The particular requirements of the task at hand determine which sorting algorithm is best, basic
or advanced. Advanced algorithms offer greater efficiency and versatility, particularly when
working with larger datasets, whereas elementary algorithms are straightforward and appropriate
for smaller datasets. The range of computational problem-solving is further expanded by shortest
path algorithms, which provide solutions for path optimization in a variety of network scenarios.
Making wise decisions in practical applications requires an understanding of these algorithms'
features and trade-offs.
Part 02
In this case, I used a queue data structure. The First-In-First-Out (FIFO) principle, which is in
line with the need to treat patients according to the order in which they are inserted into the
system, makes a queue an appropriate option. One easy and effective way to handle patients
waiting for surgeries is to create a queue.
Source Code
class Patient:
def __init__(self, admission_number, name, ward_number, age, operation_type,
blood_pressure, sugar_level):
self.admission_number = admission_number
self.name = name
self.ward_number = ward_number
self.age = age
self.operation_type = operation_type
self.blood_pressure = blood_pressure
self.sugar_level = sugar_level
self.next_patient = None
class OperationTheatre:
def __init__(self):
self.head = None
def display_patients(self):
current_patient = self.head
while current_patient:
print("Admission Number:", current_patient.admission_number)
print("Name:", current_patient.name)
print("Ward Number:", current_patient.ward_number)
print("Age:", current_patient.age)
print("Operation Type:", current_patient.operation_type)
print("Blood Pressure:", current_patient.blood_pressure)
print("Sugar Level:", current_patient.sugar_level)
print("--------------------------")
current_patient = current_patient.next_patient
def insert_patient(self):
admission_number = input("Enter Admission Number: ")
name = input("Enter Name: ")
ward_number = input("Enter Ward Number: ")
age = input("Enter Age: ")
operation_type = input("Enter Operation Type: ")
blood_pressure = input("Enter Blood Pressure: ")
sugar_level = input("Enter Sugar Level: ")
while current_patient.next_patient:
if current_patient.next_patient.admission_number == admission_number:
current_patient.next_patient = current_patient.next_patient.next_patient
print("Patient with Admission Number {} deleted
successfully.".format(admission_number))
return
current_patient = current_patient.next_patient
# Example usage:
operation_theatre = OperationTheatre()
while True:
print("\n1. Display Patients\n2. Insert Patient\n3. Update Patient\n4. Delete Patient\n5.
Exit")
choice = input("Enter your choice: ")
if choice == "1":
operation_theatre.display_patients()
elif choice == "2":
operation_theatre.insert_patient()
elif choice == "3":
admission_number = input("Enter Admission Number of the patient to update: ")
operation_theatre.update_patient(admission_number)
elif choice == "4":
admission_number = input("Enter Admission Number of the patient to delete: ")
operation_theatre.delete_patient(admission_number)
elif choice == "5":
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a valid option.")
Implementation
Figure 20
Figure 21
Test Cases
Testing is done to ensure the system runs accordingly to our expectation.
Test ID 01
Test Name Launching the system
Expected Outcome System needs to be launched
Actual Outcome
Table 1
Test ID 02
Test Name Adding patient details
Expected Outcome Details needs to be added
Actual Outcome
Table 2
Test ID 03
Test Name View inserted patient details
Expected Outcome Details should be viewed
Actual Outcome
Table 3
Table 4
Test ID 04
Test Name Update Patient
Expected Outcome Patient details should be updated
Actual Outcome
Test ID 05
Test Name Delete patient
Expected Outcome Participant should be deleted according to the given Admission
number
Actual Outcome
Table 5
Test ID 06
Test Name Exit program
Expected Outcome The program should be exit
Actual Outcome
Table 6
Test ID 07
Test Name Invalid input
Expected Outcome The program shows an error message
Actual Outcome
Table 7
Error Handling
Figure 22
Part 03
I used python for implement this operation. Because it is a versatile, high-level programming
language that offers a clear and concise syntax. This makes it easy to read and understand,
especially for beginners.
Moreover, Python is known for its simplicity and ease of use. The functions we use, such as
random.randint() for generating random numbers, are straightforward and require minimal
configuration.
Python offers robust libraries and support for algorithms and data structures, which makes it a
suitable choice for this exercise. The random library used for generating random numbers and
the list data structure used for the array are all built-in features of Python.
These reasons combined make Python a good choice for demonstrating the design and
implementation of the specified operations.
Inputs: array
Outputs: array
Preconditions: array is an integer array of size 1000
Postconditions:
- Each element in array is a random integer between 100
and 1000 (inclusive)
Source Code
import random
def create_populate_array():
array = [0] * 1000
for i in range(1000):
array[i] = random.randint(100, 1000)
return array
Inputs: array
Outputs: sortedArray
Postconditions:
- sortedArray is a sorted version of array using the
insertion sorting technique
Source Code
def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j=i-1
while j >= 0 and array[j] > key:
array[j + 1] = array[j]
j -= 1
array[j + 1] = key
3. Search the array for the values 857, 235, 78, 567, 234, 165, 1020 using binary search
algorithm:
Operation: binary_search
Inputs: sortedArray
Outputs: searchResults
Preconditions:
sortedArray is a sorted integer array of size 1000
Postconditions:
- searchResults is a set of boolean values indicating the
presence of each value in the array
Source Code
def binary_search(array, value):
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] < value:
low = mid + 1
elif array[mid] > value:
high = mid - 1
else:
return mid
return -1
Execution code
array = create_populate_array()
insertion_sort(array)
values = [857,235,78,567,234,165,1020]
for value in values:
result = binary_search(array, value)
if result != -1:
print(f"Value {value} found at index {result}")
else:
print(f"Value {value} not found in the array")
Implementation
Figure 23
Outcome
Figure 24
Value 857, 567, 234 are found in the arrays.
References
Secureuser. (2023), “Unlocking the Secrets of Efficiency: A Comprehensive Guide to Sorting
Algorithms”, Localhost, 10 August, available at: https://locall.host/why-is-sorting-algorithm-
efficient/.
Simplilearn.com. (n.d.). Queue in Data Structure & Basic Operations for Queue | Simplilearn.
[online] Available at: https://www.simplilearn.com/tutorials/data-structuretutorial/queue-in-
data-structure.
Brilliant.org. (2020). Bellman-Ford Algorithm | Brilliant Math & Science Wiki. [online]
Available at: https://brilliant.org/wiki/bellman-ford-algorithm/.
Stack Overflow. (n.d.). language agnostic - What is ADT? (Abstract Data Type). [online]
Available at: https://stackoverflow.com/questions/10267084/what-is-adt-abstract-data-type.
Tech Differences. (2016). Difference Between Data Hiding and Encapsulation (with
Comparison Chart). [online] Available at: https://techdifferences.com/difference-between-
data-hiding-and-encapsulation.html.
HNC/HND Computing 4
HNC/HND Computing 4
HNC/HND Computing 4