0% found this document useful (0 votes)
51 views42 pages

Data Structures & Algorithms

For Study Purpose Only

Uploaded by

safwan ramzeen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views42 pages

Data Structures & Algorithms

For Study Purpose Only

Uploaded by

safwan ramzeen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Pearson

Higher Nationals in

Computing

Unit 19: Data Structures & Algorithm

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.

12,34,23,56,34,78,45,78,23,78,89,4,57,3,8,9 (LO1, LO2)

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:

a. Use a formal methods notation to design the following operations.


1. Create 1000 elements integer array.
2. Populate the array with random numbers within the range of 100 to 1000.
3. Sort the array using insertion sorting technique.
4. Search the array for the values 857,235,78,567,234,165,1020 using binary search algorithm.
(LO1,LO2)
b. Using a programing language implement the above operations and if the given values are not found
test your program until it finds a value. (LO1,LO3)

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

def insert(root, key):


if root is None:
return Node(key)

if key < root.key:


root.left = insert(root.left, key)
elif key > root.key:
root.right = insert(root.right, key)

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]

for value in values:


root = insert(root, value)
Algorithm for In-order Traversal
def in_order_traversal(root):
if root:
in_order_traversal(root.left)
print(root.key, end=" ")
in_order_traversal(root.right)

# In-order traversal of the created BST


in_order_traversal(root)
Implementation

Figure 18
Outcome

Figure 19
In-order Traversal Step-by-Step

1. Visit 3: Current Node: 3, Output: [3]


2. Visit 4: Current Node: 4, Output: [3, 4]
3. Visit 8: Current Node: 8, Output: [3, 4, 8]
4. Visit 9: Current Node: 9, Output: [3, 4, 8, 9]
5. Visit 12: Current Node: 12, Output: [3, 4, 8, 9, 12]
6. Visit 23: Current Node: 23, Output: [3, 4, 8, 9, 12, 23]
7. Visit 34: Current Node: 34, Output: [3, 4, 8, 9, 12, 23, 34]
8. Visit 45: Current Node: 45, Output: [3, 4, 8, 9, 12, 23, 34, 45]
9. Visit 56: Current Node: 56, Output: [3, 4, 8, 9, 12, 23, 34, 45, 56]
10. Visit 57: Current Node: 57, Output: [3, 4, 8, 9, 12, 23, 34, 45, 56, 57]
11. Visit 78: Current Node: 78, Output: [3, 4, 8, 9, 12, 23, 34, 45, 56, 57, 78]
12. Visit 89: Current Node: 89, Output: [3, 4, 8, 9, 12, 23, 34, 45, 56, 57, 78, 89]

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.

Elementary Sorting Algorithms:


 Bubble Sort:
One of the most basic sorting algorithms is bubble sort, which works by iteratively going through
the list, comparing adjacent elements, and switching them if they are out of order. Although
Bubble Sort is conceptually simple, its O(n^2) time complexity renders it ineffective for large
datasets. Its main benefit is that it's simple, which makes it good for learning and small datasets.
 Insertion Sort:
Insertion Sort builds the final sorted array by repeatedly inserting each element into the correct
location. Insertion Sort adapts to the input order and performs well on partially sorted datasets,
despite its O(n^2) time complexity. Small datasets and situations where items are regularly
added to a list that has already been sorted tend to favor it.
 Selection Sort:
By repeatedly choosing the smallest element from the unsorted region and starting it at the
beginning, Selection Sort splits the list into sorted and unsorted regions. The time complexity of
Selection Sort is O(n^2), just like Bubble and Insertion Sort. Though its inefficiency prevents it
from being useful for large datasets, its simplicity and ease of implementation make it
appropriate for educational purposes.

Advanced Sorting Algorithms:


 Merge Sort:
A divide-and-conquer technique called merge sort divides the array recursively, sorts the two
halves, and then merges them back together. Larger datasets perform better with Merge Sort
compared to simple algorithms, with a time complexity of O(n log n). It is a popular option in
many applications due to its parallel processing compatibility, stability, and reliable
performance.
 Quick Sort:
Another divide-and-conquer algorithm called Quick Sort divides the array into partitions,
chooses a pivot element, and then sorts the partitions recursively. In the worst situation, its time
complexity can decrease to O(n^2), despite having an average time complexity of O(n log n).
Quick Sort is widely used because of its in-place sorting, average-case efficiency, and versatility,
even with this disadvantage.
 Heap Sort:
Heap Sort uses binary heaps to sort elements and is based on the heap data structure. Heap Sort
is especially efficient in practice and provides competitive performance with a time complexity
of O(n log n). Heap Sort is useful because it can be sorted in-place and is flexible enough to
work with external data structures, even though it is not as widely used as Quick or Merge Sort.

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.

Shortest Path Algorithms


Shortest path algorithms are used to find the shortest path or route between two nodes in a
network or graph. Two of the most commonly used shortest path algorithms are Dijkstra's
algorithm and Bellman Ford algorithm.
 Dijkstra's Algorithm:
Dijkstra's algorithm is a greedy algorithm that works by maintaining a set of unvisited nodes and
a set of visited nodes. Initially, the distance of all nodes is set to infinity, except for the starting
node, whose distance is set to 0. The algorithm then selects the node with the minimum distance
from the starting node and visits its neighbors, updating their distances if necessary. This process
continues until the destination node is reached or all nodes have been visited.

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 add_patient(self, patient):


if not self.head:
self.head = patient
else:
current_patient = self.head
while current_patient.next_patient:
current_patient = current_patient.next_patient
current_patient.next_patient = patient

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: ")

new_patient = Patient(admission_number, name, ward_number, age, operation_type,


blood_pressure, sugar_level)
self.add_patient(new_patient)
def update_patient(self, admission_number):
current_patient = self.head
while current_patient:
if current_patient.admission_number == admission_number:
# You can add logic here to update patient information
# For example:
current_patient.name = input("Enter updated Name: ")
current_patient.ward_number = input("Enter updated Ward Number: ")
current_patient.age = input("Enter updated Age: ")
current_patient.operation_type = input("Enter updated Operation Type: ")
current_patient.blood_pressure = input("Enter updated Blood Pressure: ")
current_patient.sugar_level = input("Enter updated Sugar Level: ")
print("Patient information updated successfully.")
return
current_patient = current_patient.next_patient
print("Patient with Admission Number {} not found.".format(admission_number))

def delete_patient(self, admission_number):


current_patient = self.head
if current_patient and current_patient.admission_number == admission_number:
self.head = current_patient.next_patient
print("Patient with Admission Number {} deleted
successfully.".format(admission_number))
return

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

print("Patient with Admission Number {} not found.".format(admission_number))

# 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.

Documentation and Program source code


1. Create 1000 elements integer array and populate the array with random numbers within
the range of 100 to 1000:
Operation: create_populate_array

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

2. Sort the array using insertion sorting technique:


Operation: insertion_sort

Inputs: array
Outputs: sortedArray

Preconditions: array is an integer array of size 1000

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/.

Ramuglia, G. (2023), “Python Sort Algorithms: A Comprehensive Guide”, Linux Dedicated


Server Blog, 21 November, available at: https://ioflood.com/blog/python-sort-algorithms/.

“Sorting algorithm”. (2023), Wikipedia, 3 November, available at:


https://en.wikipedia.org/wiki/Sorting_algorithm.

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.

programmer.help. (n.d.). Queue data structure. [online] Available at:


https://programmer.help/blogs/queue-data-structure.html [Accessed 28 Mar. 2023].

Brilliant.org. (2020). Bellman-Ford Algorithm | Brilliant Math & Science Wiki. [online]
Available at: https://brilliant.org/wiki/bellman-ford-algorithm/.

GeeksforGeeks (2017). Abstract Data Types - GeeksforGeeks. [online] GeeksforGeeks.


Available at: https://www.geeksforgeeks.org/abstract-data-types/.

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.

www.tutorialandexample.com. (n.d.). Dijkstra’s vs Bellman-Ford Algorithm - TAE. [online]


Available at: https://www.tutorialandexample.com/dijkstras-vs-bellman-ford-algorithm
[Accessed 28 Mar. 2023].

programming.vip. (n.d.). Shortest path algorithm. [online] Available at:


https://programming.vip/docs/shortest-path-algorithm.html [Accessed 28 Mar. 2023].

HNC/HND Computing 4
HNC/HND Computing 4
HNC/HND Computing 4

You might also like