Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Understanding Abstract Data Types (ADTs) and Their Role in Software Development, Study Guides, Projects, Research of Data Structures and Algorithms

A comprehensive guide to abstract data types (adts), focusing on their role in software development, particularly in the context of object-oriented programming. It covers the concepts of imperative adts, their implementation in various programming languages, and their integration into object-oriented paradigms. The document also discusses the advantages of encapsulation and information hiding in adts, and provides examples to illustrate the relationship between imperative adts and object-oriented programming.

Typology: Study Guides, Projects, Research

2023/2024

Uploaded on 03/02/2024

manh-phan-tuan
manh-phan-tuan 🇻🇳

2 documents

1 / 92

Toggle sidebar

Related documents


Partial preview of the text

Download Understanding Abstract Data Types (ADTs) and Their Role in Software Development and more Study Guides, Projects, Research Data Structures and Algorithms in PDF only on Docsity! ASSIGNMENT 1 FRONT SHEET Qualification BTEC Level 5 HND Diploma in Computing Unit number and title Unit 19: Data Structures and Algorithms Submission date 10/10/2023 Date Received 1st submission Re-submission Date Date Received 2nd submission Student Name Phan Tuan Manh Student ID BH00210 Class IT0503 Assessor name Ta Quang Hieu Student declaration I certify that the assignment submission is entirely my own work and I fully understand the consequences of plagiarism. I understand that making a false declaration is a form of malpractice. Student’s signature Grading grid P1 P2 P3 M1 M2 M3 D1 D2 1 | P a g e  Summative Feedback:  Resubmission Feedback: Grade: Assessor Signature: Date: Internal Verifier’s Comments: IV Signature: 2 | P a g e FIGURE 1: ABSTRACT DATA TYPE.------------------------------------------------------------------------------------------------------------------------------10 FIGURE 2: STACK ADT-------------------------------------------------------------------------------------------------------------------------------------------11 FIGURE 3: STACK OPERATIONS----------------------------------------------------------------------------------------------------------------------------------13 FIGURE 4: IMPLEMENTATION OF A STACK ADT (1)-----------------------------------------------------------------------------------------------------------14 FIGURE 5: IMPLEMENTATION OF A STACK ADT (2)-----------------------------------------------------------------------------------------------------------15 FIGURE 6: IMPLEMENTATION OF A STACK ADT (3)-----------------------------------------------------------------------------------------------------------16 FIGURE 7: EXAMPLE MEMORY STACK FOR FUNCTION CALLS-------------------------------------------------------------------------------------------------21 FIGURE 8: QUEUE DATA STRUCTURE (GEEKSFORGEEKS, 2023)----------------------------------------------------------------------------------------------22 FIGURE 9: FIFO PROPERTY IN QUEUE (GEEKSFORGEEKS, 2023)----------------------------------------------------------------------------------------------23 FIGURE 10: FIFO QUEUE USING JAVA (1)----------------------------------------------------------------------------------------------------------------------24 FIGURE 11: FIFO QUEUE USING JAVA (2)----------------------------------------------------------------------------------------------------------------------25 FIGURE 12: BUBBLE SORT FLOW CHART------------------------------------------------------------------------------------------------------------------------33 FIGURE 13: BUBBLE SORT ALGORITHM : PLACING THE LARGEST ELEMENT AT CORRECT POSITION (GEEKSFORGEEKS, 2023)----------------------------34 FIGURE 14: BUBBLE SORT ALGORITHM : PLACING THE SECOND LARGEST ELEMENT AT CORRECT POSITION (GEEKSFORGEEKS, 2023)-------------------35 FIGURE 15: BUBBLE SORT ALGORITHM : PLACING THE REMAINING ELEMENTS AT THEIR CORRECT POSITIONS (GEEKSFORGEEKS, 2023)---------------35 FIGURE 16: IMPLEMENTATION OF BUBBLE SORT (1)----------------------------------------------------------------------------------------------------------37 FIGURE 17: IMPLEMENTATION OF BUBBLE SORT (2)----------------------------------------------------------------------------------------------------------38 FIGURE 18: SELECTION SORT FLOW CHART---------------------------------------------------------------------------------------------------------------------40 FIGURE 19: SELECTION SORT ALGORITHM | SWAPPING 1ST ELEMENT WITH THE MINIMUM IN ARRAY (GEEKSFORGEEKS, 2023)-----------------------41 FIGURE 20: SELECTION SORT ALGORITHM | SWAPPING I=1 WITH THE NEXT MINIMUM ELEMENT (GEEKSFORGEEKS, 2023)----------------------------42 FIGURE 21: SELECTION SORT ALGORITHM | SWAPPING I=2 WITH THE NEXT MINIMUM ELEMENT (GEEKSFORGEEKS, 2023)----------------------------42 FIGURE 22: SELECTION SORT ALGORITHM | SWAPPING I=3 WITH THE NEXT MINIMUM ELEMENT (GEEKSFORGEEKS, 2023)----------------------------43 FIGURE 23: SELECTION SORT ALGORITHM | REQUIRED SORTED ARRAY (GEEKSFORGEEKS, 2023)---------------------------------------------------------43 FIGURE 24: IMPLEMENTATION OF SELECTION SORT (1)-------------------------------------------------------------------------------------------------------44 FIGURE 25: IMPLEMENTATION OF SELECTION SORT (2)-------------------------------------------------------------------------------------------------------45 FIGURE 26: EXAMPLE SHORTEST PATH ALGORITHM------------------------------------------------------------------------------------------------------------46 FIGURE 27: DIJKSTRA’S ALGORITHM FLOW CHART------------------------------------------------------------------------------------------------------------48 FIGURE 28: DIJKSTRA’S ALGORITHM----------------------------------------------------------------------------------------------------------------------------49 FIGURE 29: DIJKSTRA’S ALGORITHM STEP 1-------------------------------------------------------------------------------------------------------------------50 FIGURE 30: DIJKSTRA’S ALGORITHM STEP 2-------------------------------------------------------------------------------------------------------------------51 FIGURE 31: DIJKSTRA’S ALGORITHM STEP 3-------------------------------------------------------------------------------------------------------------------52 FIGURE 32: DIJKSTRA’S ALGORITHM STEP 4-------------------------------------------------------------------------------------------------------------------53 FIGURE 33: DIJKSTRA’S ALGORITHM STEP 5-------------------------------------------------------------------------------------------------------------------54 FIGURE 34: IMPLEMENTATION OF DIJKSTRA’S ALGORITHM (1)-----------------------------------------------------------------------------------------------55 FIGURE 35: IMPLEMENTATION OF DIJKSTRA’S ALGORITHM (2)-----------------------------------------------------------------------------------------------56 FIGURE 36: IMPLEMENTATION OF DIJKSTRA’S ALGORITHM (3)-----------------------------------------------------------------------------------------------56 FIGURE 37: INITIAL GRAPH (GEEKSFORGEEKS, 2023).--------------------------------------------------------------------------------------------------------58 FIGURE 38: INITIALIZE A DISTANCE ARRAY (GEEKSFORGEEKS, 2023).----------------------------------------------------------------------------------------59 FIGURE 39: 1ST RELAXATION (GEEKSFORGEEKS, 2023).------------------------------------------------------------------------------------------------------60 FIGURE 40: 2ND RELAXATION (GEEKSFORGEEKS, 2023).-----------------------------------------------------------------------------------------------------61 FIGURE 41: 3RD RELAXATION (GEEKSFORGEEKS, 2023).-----------------------------------------------------------------------------------------------------62 FIGURE 42: 4TH RELAXATION (GEEKSFORGEEKS, 2023).-----------------------------------------------------------------------------------------------------63 FIGURE 43: 5TH RELAXATION (GEEKSFORGEEKS, 2023).-----------------------------------------------------------------------------------------------------64 FIGURE 44: 6TH RELAXATION (GEEKSFORGEEKS, 2023).-----------------------------------------------------------------------------------------------------65 FIGURE 45: IMPLEMENTATION OF BELLMAN-FORD’S ALGORITHM (1)---------------------------------------------------------------------------------------66 FIGURE 46: IMPLEMENTATION OF BELLMAN-FORD’S ALGORITHM (2)---------------------------------------------------------------------------------------67 5 | P a g e FIGURE 47: IMPLEMENTATION OF BELLMAN-FORD’S ALGORITHM (3)---------------------------------------------------------------------------------------68 FIGURE 48: IMPLEMENTATION OF BELLMAN-FORD’S ALGORITHM (4)---------------------------------------------------------------------------------------69 FIGURE 49: OPERATION: PUSH(ITEM)--------------------------------------------------------------------------------------------------------------------------73 FIGURE 50: OPERATION: POP()---------------------------------------------------------------------------------------------------------------------------------74 FIGURE 51: OPERATION: PEEK()--------------------------------------------------------------------------------------------------------------------------------74 FIGURE 52: OPERATION: ISEMPTY()----------------------------------------------------------------------------------------------------------------------------75 FIGURE 53: OPERATION: SIZE()---------------------------------------------------------------------------------------------------------------------------------76 FIGURE 54: UNDO/REDO FUNCTIONALITY IN A TEXT EDITOR--------------------------------------------------------------------------------------------------77 FIGURE 55: ENCAPSULATION USING ACCESSORS AND MUTATORS-------------------------------------------------------------------------------------------82 FIGURE 56: ENCAPSULATION USING PROPERTIES--------------------------------------------------------------------------------------------------------------83 FIGURE 57: IMPERATIVE ADT-----------------------------------------------------------------------------------------------------------------------------------87 FIGURE 58: IMPERATIVE OOP----------------------------------------------------------------------------------------------------------------------------------88 6 | P a g e I. Introduction In the ever-evolving landscape of software development, innovation and efficiency are key drivers of success. As an in-house software developer at Softnet Development Ltd, a renowned provider of network provisioning solutions, I find myself immersed in a compelling scenario. Our company is an integral part of a collaborative service provisioning development project, and I have proudly secured the contract to design and develop a middleware solution that will serve as the crucial interface connecting multiple computer provisioning interfaces, including SOAP, HTTP, JML, and CLI, with the telecom provisioning network at the back end via CLI. Within this challenging context, my account manager has entrusted me with a special role: to guide and inform our team on the intricacies of designing and implementing abstract data types (ADTs). This assignment calls for the creation of a presentation that will be shared with our esteemed collaborating partners, shedding light on how ADTs can be harnessed to enhance every aspect of software development, from design to testing. Moreover, I have been tasked with crafting an introductory report, which will be distributed to all project partners. This report aims to provide a comprehensive understanding of how to specify abstract data types and algorithms using a formal notation. It will delve into the core principles of ADTs and their potential to elevate software engineering practices. The primary objectives of this report are as follows: 1. Explanation on how to specify an abstract data type using the example of a software stack: In this report, I will elucidate the process of defining and specifying an abstract data type, employing the practical example of a software stack. This will serve as a foundation for comprehending the broader concepts related to ADTs. 2. Explanation of the advantages of encapsulation and information hiding when using an ADT: One of the core principles of ADTs is encapsulation, which promotes the concealment of implementation details. I will explore the significance of encapsulation and information hiding in the context of ADTs, highlighting the benefits they bring to software development. 3. Discussion of imperative ADTs with regard to object orientation: 7 | P a g e is implemented using Tree map, hash map, or hash table (Abstract data type in data structure - javatpoint). The process of providing only the essentials and hiding the details is known as abstraction. Figure 1: Abstract Data Type. The user of data type does not need to know how that data type is implemented, for example, we have been using Primitive values like int, float, char data types only with the knowledge that these data type can operate and be performed on without any idea of how they are implemented. So a user only needs to know what a data type can do, but not how it will be implemented. Think of ADT as a black box which hides the inner structure and design of the data type (geeksforgeeks, 2023). To further elucidate the concept of an Abstract Data Type (ADT), we will employ the example of a software stack. A stack is a prime illustration of an ADT, showcasing its essential characteristics. 3. Stack ADT To underscore the definition of an Abstract Data Type (ADT), we'll delve into the example of a software stack. A stack serves as an exemplary manifestation of the ADT concept. 10 | P a g e As previously outlined, an ADT is an abstract programming notion. It describes a set of data and operations on that data without specifically revealing the underlying structure or algorithms. In the context of a software stack, this ADT adheres to the Last-In-First-Out (LIFO) principle. LIFO( Last In First Out ): This strategy states that the element that is inserted last will come out first. You can take a pile of plates kept on top of each other as a real-life example. The plate which we put last is on the top and since we remove the plate that is at the top, we can say that the plate that was put last comes out first (Introduction to stack - data structure and algorithm tutorials, 2023). Figure 2: Stack ADT By examining the stack ADT, we can emphasize the core concept of ADTs. It demonstrates how ADTs provide a clear interface and define the permissible operations on the data structure, abstracting away the underlying complexities of implementation. This example of a software stack serves as a concrete manifestation of the ADT concept, highlighting the power of abstraction in software development. 3.1 Stack operations and working mechanism In order to make manipulations in a stack, there are certain operations provided to us. 11 | P a g e  push() to insert an element into the stack  pop() to remove an element from the stack  top() Returns the top element of the stack.  isEmpty() returns true if stack is empty else false.  size() returns the size of stack. Figure 3: Stack operations 12 | P a g e Figure 6: Implementation of a Stack ADT (3) This implementation defines a generic Stack class that can work with any data type. It includes methods for pushing, popping, peeking at the top element, checking if the stack is empty or full, and displaying the contents of the stack. The example usage at the end demonstrates how to use this Stack ADT in Java. 15 | P a g e 3.3 Applications/Examples of Stack Stacks are fundamental data structures that find application in various real-world scenarios. Here are some examples of how stacks are used in practical situations: Function Call Management: Stacks are widely used in programming languages to manage function calls. When a function is called, its local variables and parameters are stored in a stack frame. As functions return, their stack frames are popped from the stack. Undo Functionality in Software: In many software applications, such as text editors or graphic design tools, stacks are used to implement undo and redo functionality. Each state of the application is pushed onto a stack, allowing users to go back to previous states. Expression Evaluation: Stacks are utilized in parsing and evaluating mathematical expressions, such as arithmetic expressions or expressions in programming languages. They help maintain the correct order of operations. Browser History: Web browsers use stacks to keep track of the user's navigation history. Each visited page is pushed onto the stack, and the back and forward buttons pop pages from the stack. Backtracking Algorithms: Algorithms that involve backtracking, like depth-first search (DFS) and recursive algorithms, use stacks to keep track of the state of the search and return to previous states. Call Stack in Multithreading: In multithreaded applications, each thread has its own call stack. Stacks are used to manage the execution context of each thread, including function calls and local variables. Balancing Parentheses: Stacks are employed to check for balanced parentheses in expressions. As open and close brackets are encountered, they are pushed and popped from the stack. If the stack is empty at the end, the expression is balanced. Task Scheduling: Stacks can be used in task scheduling algorithms to keep track of tasks that need to be executed. The last task added is the first to be executed (Last-In-First-Out, or LIFO). 16 | P a g e P2 Determine the operations of a memory stack and how it is used to implement function calls in a computer In Part P2, I will delve into the operations of a memory stack and explore how it plays a vital role in the execution of function calls within a computer system. 1. Memory Stack A stack is a special area of computer’s memory which stores temporary variables created by a function. In stack, variables are declared, stored and initialized during runtime. It is a temporary storage memory. When the computing task is complete, the memory of the variable will be automatically erased. The stack section mostly contains methods, local variable, and reference variables (Matthew Martin & Martin, 2023). 2. Operations of a Memory Stack  Push Operation: This operation is used to insert a new data item into the top of the Stack. The new item can be inserted as follows:- SP ←SP-1 M[SP]← DR In the first step, the Stack Pointer is decremented to point at the address where the data item will be stored. Then, by using the memory write operation, the data item from Data Register gets inserted into the top of the stack ( at the address where the Stack Pointer is pointing) (Memory Stack Organization in computer architecture, 2023). 17 | P a g e Figure 7: Example Memory Stack for Function Calls In this Java example: The main function is the entry point of the program. When the main function is called, it pushes its activation record onto the memory stack, including the return address for when it completes execution. The add function is called from within the main function. When the add function is called, its activation record is pushed onto the stack, and it calculates the sum of a and b. After completing its execution, the add function pops its activation record from the stack, and control returns to the main function. Finally, the main function completes its execution, and its activation record is popped from the stack. This example demonstrates how the memory stack is used to manage the execution context of functions, allowing them to be called and return control to their respective callers. 20 | P a g e M1 Illustrate, with an example, a concrete data structure for a First In First out (FIFO) queue. 1. Queue Data Structure A Queue is defined as a linear data structure that is open at both ends and the operations are performed in First In First Out (FIFO) order. We define a queue to be a list in which all additions to the list are made at one end, and all deletions from the list are made at the other end. The element which is first pushed into the order, the operation is first performed on that (geeksforgeeks, 2023). Figure 8: Queue Data Structure (geeksforgeeks, 2023) 2. FIFO Principle of Queue A Queue is like a line waiting to purchase tickets, where the first person in line is the first person served. (i.e. First come first serve). Position of the entry in a queue ready to be served, that is, the first entry that will be removed from the queue, is called the front of the queue(sometimes, head of the queue), similarly, the position of the last 21 | P a g e entry in the queue, that is, the one most recently added, is called the rear (or the tail) of the queue. See the below figure (geeksforgeeks, 2023). Figure 9: Fifo Property in Queue (geeksforgeeks, 2023) 3. Implementation of FIFO Queue Provide a concrete example to demonstrate how the FIFO queue works and how it is used. This example should include adding elements to the queue, removing elements from the queue, and accessing the first element. Here is an example of how you can implement and illustrate a FIFO queue using Java: 22 | P a g e M2 Compare the performance of two sorting algorithms. 1. Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure (geeksforgeeks, 2023). 1.1 The Purpose of Sorting The purpose of sorting in computer science and data processing is to arrange a collection of data or elements in a specific order, often in a particular sequence or pattern. Sorting serves several important purposes in various applications:  Data Retrieval Efficiency: Sorting allows for efficient data retrieval. When data is sorted, it becomes easier and quicker to locate specific items or perform searches using algorithms like binary search. This is particularly critical in databases, where quick data retrieval is essential.  Improved Data Presentation: Sorted data is often presented in a more organized and user- friendly manner. For example, sorted lists or tables make it easier for users to find and comprehend information.  Algorithmic Requirements: Many algorithms and data structures, such as binary search trees, hash tables, and merge sort, rely on sorted data for their efficient operation. Sorting data beforehand can significantly improve the performance of these algorithms.  Data Analysis: In data analysis and statistics, sorting data can help identify patterns, trends, and outliers. Sorting is often a preliminary step in data analysis to facilitate subsequent calculations and visualizations.  Optimizing Input for Algorithms: Some algorithms work more efficiently on sorted data. For example, many divide-and-conquer algorithms, like merge sort and quicksort, work optimally or near-optimally when applied to sorted or partially sorted data. 25 | P a g e  Data Presentation and Reporting: Sorted data is often more aesthetically pleasing and easier to understand when presenting information to users or stakeholders. Reports, charts, and graphs are more comprehensible when data is ordered logically.  Data Aggregation: Sorting is useful when aggregating data. For example, when summarizing data for a time period, sorting timestamps or dates allows for easier grouping and calculation.  Search Engine Optimization: In web search engines, sorting is used to rank search results based on relevance. Search engine algorithms often use sorting to present the most relevant search results to users.  Database Operations: Sorting is integral in database systems for performing various operations like sorting query results, creating indexes, and optimizing query execution plans.  Algorithmic Challenges and Competitions: Sorting algorithms are classic examples of algorithmic challenges. They are frequently used as benchmarks for evaluating algorithm performance and as competitive programming problems. In summary, the purpose of sorting is to bring order and structure to data, making it more accessible, efficient, and meaningful for various computational and analytical tasks. It is a fundamental operation in computer science and data processing, with a wide range of applications across different domains. 1.2 Different Sorting Algorithms There are several sorting algorithms in computer science, each with its own approach and characteristics. Here are some of the most commonly used sorting algorithms: 1. Bubble Sort: - Simple and easy to implement. - It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. - Inefficient for large lists, as it has a time complexity of O(n^2) in the worst case. 26 | P a g e 2. Selection Sort: - It divides the list into a sorted and an unsorted region, repeatedly selects the smallest element from the unsorted region, and moves it to the sorted region. - It also has a time complexity of O(n^2) in the worst case. 3. Insertion Sort: - It builds a sorted list one item at a time by repeatedly taking the next unsorted element and inserting it into the correct position within the sorted part of the list. - It is efficient for small lists but has a time complexity of O(n^2) in the worst case. 4. Merge Sort: - It uses a divide-and-conquer strategy, dividing the list into smaller sublists until they are sorted and then merging them. - It has a time complexity of O(n log n) in the worst case, making it more efficient than bubble, selection, and insertion sorts for large lists. 5. Quick Sort: - It also uses a divide-and-conquer approach, selecting a "pivot" element and partitioning the list into elements smaller and larger than the pivot. - It has an average time complexity of O(n log n) but can degrade to O(n^2) in the worst case. 6. Heap Sort: - It builds a binary heap data structure from the list and repeatedly extracts the maximum element to build the sorted list. - It has a time complexity of O(n log n) in the worst case. 7. Radix Sort: - It sorts numbers by considering each digit or character in the elements. 27 | P a g e Bubble Sort: Advantaged Disadvantaged Bubble sort is easy to understand and implement. Bubble sort has a time complexity of O(N2) which makes it very slow for large data sets. It does not require any additional memory space. Bubble sort is a comparison-based sorting algorithm, which means that it requires a comparison operator to determine the relative order of elements in the input data set. It can limit the efficiency of the algorithm in certain cases. It is a stable sorting algorithm, meaning that elements with the same key value maintain their relative order in the sorted output (geeksforgeeks, 2023). Selection Sort: Advantaged Disadvantaged Simple and easy to understand. Selection sort has a time complexity of O(n^2) in the worst and average case. Works well with small datasets. Does not work well on large datasets. Does not preserve the relative order of items with equal keys which means it is not stable (geeksforgeeks, 2023). 2. Bubble Sort Algorithm: In this algorithm: 30 | P a g e  Traverse from left and compare adjacent elements and the higher one is placed at right side.  In this way, the largest element is moved to the rightmost end at first.  This process is then continued to find the second largest and place it and so on until the data is sorted. 2.1 How does Bubble Sort Work? Flow Chart: This flow chart will explain for how does Bubble sort algorithm work 31 | P a g e Figure 12: Bubble Sort flow chart And for more understand the working of bubble sort with the help of the following illustration: Input: arr[] = {6, 3, 0, 5} First Pass: The largest element is placed in its correct position, i.e., the end of the array. 32 | P a g e Figure 16: Implementation of Bubble Sort (1) 35 | P a g e Figure 17: Implementation of Bubble Sort (2) Output: Sorted array: 11 12 22 25 34 64 90 2.3 Time Complexity Best Case Sorted array as input. Or almost all elements are in proper place. [ O(N) ]. O(1) swaps. Worst Case: Reversely sorted / Very few elements are in proper place. [ O(N2) ] . O(N2) swaps. Average Case: [ O(N2) ] . O(N2) swaps. 36 | P a g e 3. Selection Sort Algorithm: Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the list. 3.1 How does Selection Sort Algorithm work? Flow Chart: This flow chart will explain for how does Selection sort algorithm work 37 | P a g e Figure 20: Selection Sort Algorithm | swapping i=1 with the next minimum element (geeksforgeeks, 2023) Third Pass: Now, for third place, where 25 is present again traverse the rest of the array and find the third least value present in the array. While traversing, 22 came out to be the third least value and it should appear at the third place in the array, thus swap 22 with element present at third position. Figure 21: Selection Sort Algorithm | swapping i=2 with the next minimum element (geeksforgeeks, 2023) Fourth pass: Similarly, for fourth position traverse the rest of the array and find the fourth least element in the array 40 | P a g e As 25 is the 4th lowest value hence, it will place at the fourth position. Figure 22: Selection Sort Algorithm | swapping i=3 with the next minimum element (geeksforgeeks, 2023) Fifth Pass: At last the largest value present in the array automatically get placed at the last position in the array The resulted array is the sorted array. Figure 23: Selection Sort Algorithm | Required sorted array (geeksforgeeks, 2023) 41 | P a g e 3.2 Implementation of Bubble Sort Below is the implementation of the bubble sort. It can be optimized by stopping the algorithm if the inner loop didn’t cause any swap. Figure 24: Implementation of Selection Sort (1) 42 | P a g e In Module D1, I will conduct an in-depth analysis of two network shortest path algorithms: Bellman-Ford and Dijkstra. These algorithms play a crucial role in finding the shortest path between nodes in a network, making them essential in various applications, including routing in computer networks and GPS navigation systems 2. Dijkstra Algorithm Dijkstra’s algorithm is a popular algorithms for solving many single-source shortest path problems having non-negative edge weight in the graphs i.e., it is to find the shortest distance between two vertices on a graph. It was conceived by Dutch computer scientist Edsger W. Dijkstra in 1956. The algorithm maintains a set of visited vertices and a set of unvisited vertices. It starts at the source vertex and iteratively selects the unvisited vertex with the smallest tentative distance from the source. It then visits the neighbors of this vertex and updates their tentative distances if a shorter path is found. This process continues until the destination vertex is reached, or all reachable vertices have been visited (geeksforgeeks, 2023). 2.1 How does Dijkstra’s Algorithm works? Flow Chart: 45 | P a g e Figure 27: Dijkstra’s Algorithm Flow Chart Let’s see how Dijkstra’s Algorithm works with an example given below: Dijkstra’s Algorithm will generate the shortest path from Node 0 to all other Nodes in the graph. Consider the below graph: 46 | P a g e Figure 28: Dijkstra’s Algorithm The algorithm will generate the shortest path from node 0 to all the other nodes in the graph. For this graph, we will assume that the weight of the edges represents the distance between two nodes. As, we can see we have the shortest path from, Node 0 to Node 1, from Node 0 to Node 2, from Node 0 to Node 3, from Node 0 to Node 4, from Node 0 to Node 6. Initially we have a set of resources given below : 47 | P a g e Figure 31: Dijkstra’s Algorithm step 3 Step 4: Again we have two choices for adjacent Nodes (Either we can choose Node 4 with distance 10 or either we can choose Node 5 with distance 15) so choose Node with minimum distance. In this step Node 4 is Minimum distance adjacent Node, so marked it as visited and add up the distance. Distance: Node 0 -> Node 1 -> Node 3 -> Node 4 = 2 + 5 + 10 = 17 50 | P a g e Figure 32: Dijkstra’s Algorithm step 4 Step 5: Again, Move Forward and check for adjacent Node which is Node 6, so marked it as visited and add up the distance, Now the distance will be: Distance: Node 0 -> Node 1 -> Node 3 -> Node 4 -> Node 6 = 2 + 5 + 10 + 2 = 19 51 | P a g e Figure 33: Dijkstra’s Algorithm step 5 2.2 Implementation of Dijkstra’s Algorithm Below is the implementation of the above approach: This implementation assumes you have a graph represented as an adjacency matrix and aims to find the shortest path from a source node to all other nodes in the graph. Here's a Java implementation of Dijkstra's algorithm: 52 | P a g e Output: Vertex Distance from Source 0 0 1 4 2 12 3 19 4 26 5 16 2.3 Time Complexity Best Case Complexity O(E) Average Case Complexity O(VE) Worst Case Complexity O(VE) 3. Bellman-Ford Algorithm Bellman-Ford is a single source shortest path algorithm that determines the shortest path between a given source vertex and every other vertex in a graph. This algorithm can be used on both weighted and unweighted graphs. A Bellman-Ford algorithm is also guaranteed to find the shortest path in a graph, similar to Dijkstra’s algorithm. Although Bellman-Ford is slower than Dijkstra’s algorithm, it is capable of handling graphs with negative edge weights, which makes it more versatile. The shortest path cannot be found if there exists a negative cycle in the graph. If we continue to go around the negative cycle an infinite number of times, then the cost of the path will continue to decrease (even though the length of the path is 55 | P a g e increasing). As a result, Bellman-Ford is also capable of detecting negative cycles, which is an important feature (geeksforgeeks, 2023). 3.1 How does Bellman-Ford’s Algorithm works? Let’s see how Bellman-Ford’s Algorithm works with an example given below: I have a graph which is given below and I want to find whether there exists a negative cycle or not using Bellman-Ford. Figure 37: Initial Graph (geeksforgeeks, 2023). Step 1: Initialize a distance array Dist[] to store the shortest distance for each vertex from the source vertex. Initially distance of source will be 0 and Distance of other vertices will be INFINITY. 56 | P a g e Figure 38: Initialize a distance array (geeksforgeeks, 2023). Step 2: Start relaxing the edges, during 1st Relaxation: Current Distance of B > (Distance of A) + (Weight of A to B) i.e. Infinity > 0 + 5 Therefore, Dist[B] = 5 57 | P a g e Figure 41: 3rd Relaxation (geeksforgeeks, 2023). Step 5: During 4th Relaxation: Current Distance of D > (Distance of E) + (Weight of E to D) i.e. 7 > 7 + (-1) Dist[D] = 6 Current Distance of E > (Distance of F ) + (Weight of F to E) i.e. 7 > 9 + (-3) Dist[E] = 6 60 | P a g e Figure 42: 4th Relaxation (geeksforgeeks, 2023). Step 6: During 5th Relaxation: Current Distance of F > (Distance of D) + (Weight of D to F) i.e. 9 > 6 + 2 Dist[F] = 8 Current Distance of D > (Distance of E ) + (Weight of E to D) i.e. 6 > 6 + (-1) Dist[E] = 5 Since the graph h 6 vertices, So during the 5th relaxation the shortest distance for all the vertices should have been calculated. 61 | P a g e Figure 43: 5th Relaxation (geeksforgeeks, 2023). Step 7: Now the final relaxation i.e. the 6th relaxation should indicate the presence of negative cycle if there is any changes in the distance array of 5th relaxation. During the 6th relaxation, following changes can be seen: Current Distance of E > (Distance of F) + (Weight of F to E) i.e. 6 > 8 + (-3) Dist[E]=5 Current Distance of F > (Distance of D ) + (Weight of D to F) i.e. 8 > 5 + 2 Dist[F]=7 Since, we observer changes in the Distance array Hence ,we can conclude the presence of a negative cycle in the graph. 62 | P a g e Figure 46: Implementation of Bellman-Ford’s Algorithm (2) 65 | P a g e Figure 47: Implementation of Bellman-Ford’s Algorithm (3) 66 | P a g e Figure 48: Implementation of Bellman-Ford’s Algorithm (4) Output: Vertex Distance from Source 0 0 1 -1 67 | P a g e 2.1 Pre-condition: Definition: A pre-condition is a condition or set of conditions that must be true or satisfied before an operation or function is executed. Purpose: Pre-conditions are used to specify the requirements or constraints that must be met for the operation to work correctly. They define the state in which an operation is valid. 2.2 Post-condition: Definition: A post-condition is a condition or set of conditions that must be true after an operation or function has been executed. Purpose: Post-conditions describe the expected state of the system, data, or variables after the operation's completion. They ensure that the operation has achieved its intended effect. 2.3 Error-condition: Definition: An error-condition, also known as an exception or error-handling condition, defines what happens when an operation encounters an exceptional situation or error during its execution. Purpose: Error-conditions specify how errors or exceptional cases are handled within an operation. They describe the actions or behaviors to be taken when something unexpected occurs. Pre-conditions set the stage for an operation, post-conditions define the desired outcome, and error- conditions handle unexpected situations or errors that may arise during the operation's execution. These conditions are crucial for providing clarity and correctness in software specifications and ensuring the robustness of software systems. 3. Specification of Stack Operations 3.1 Operation: push(item) Purpose: Adds an item to the top of the stack. Pre-condition: The stack exists. Post-condition: The item item is now at the top of the stack. The stack's size has increased by one. 70 | P a g e Error-condition: If the stack has a defined maximum size and is full, an error should be thrown. Java Code: Figure 49: Operation: push(item) 3.2 Operation: pop() Purpose: Removes and returns the top item from the stack. Pre-condition: The stack is not empty. Post-condition: The top item has been removed from the stack. The stack's size has decreased by one. Error-condition: If the stack is empty, an error should be thrown. Java Code: 71 | P a g e Figure 50: Operation: pop() 3.3 Operation: peek() Purpose: Returns the top item without removing it. Pre-condition: The stack is not empty. Post-condition: The stack remains unchanged. Error-condition: If the stack is empty, an error should be thrown. Java Code: Figure 51: Operation: peek() 72 | P a g e Figure 54: undo/redo functionality in a text editor In this example: We have a TextEditor class that maintains a StringBuilder to store the text content. I use two stacks, undoStack and redoStack, to keep track of previous states for undo and redo operations. The insertText method is used to insert new text, and it pushes the current state onto the undo stack. 75 | P a g e The undo method pops the last state from the undo stack and restores it while pushing the current state onto the redo stack. The redo method pops the next state from the redo stack and restores it while pushing the current state onto the undo stack. We can observe the behavior by inserting text, undoing changes, and redoing changes. M3 Examine the advantages of encapsulation and information hiding when using an ADT. In this section, we will delve into the advantages of encapsulation and information hiding when using an Abstract Data Type (ADT) while also considering the roles of Read-only and Write-only properties within this context. 76 | P a g e 1. Understanding Encapsulation and Information Hiding Firstly, let's clarify the concepts of encapsulation and information hiding within the realm of object- oriented programming: 1.1 Encapsulation Encapsulation is binding the code and data together in a capsule to hide the complexity of a class. Encapsulation has less to do with access specifiers (private, public and protected). In encapsulation members inside a class can be private, public or protected. The private members of a class are only accessible to the objects of that class only, and the public members are accessible to the objects of the class as well as they are accessible from outside the class. Encapsulation helps the end user of a system to learn what to do with the system instead of how it must do. Let us understand encapsulation with the help of an example of a car. If a driver of a car wants to change the gear of car, what he needs is to just change the position of the liver operating gears of the car and it thus changes the gear of a car. A driver does not need to understand the complexity of, what is the mechanism behind changing the gear. This is how encapsulation reduces the complexity of a system. Encapsulation makes the system easier to operate by the end user.. (Bhakti, 2019). Why we need encapsulation: Encapsulation is important because it provides a powerful way to store, hide, and manipulate data while giving you increased control over it. Encapsulation can used when dealing with secure data or methods because it can restrict which functions or users have access to certain information. Encapsulation is a key concept in object-oriented programming (OOP), where everything revolves around objects. In OOP programming, a class is a blueprint for creating objects. It defines the properties and behaviors that objects of a certain class can have. Classes specify what data an object can have (attributes) and what it can do (methods). A class bundles its attributes and methods through encapsulation, protecting the data. Encapsulation is also used to protect information from being modified or having new errors introduced. When you store and lock the information in a bundle, it is much more difficult for users to accidentally modify the information. You achieve this by making the data private, meaning you can 77 | P a g e To achieve encapsulation, classes often use accessors (getters) and mutators (setters). Accessors allow reading data, and mutators allow modifying it. This separation of access and modification control ensures data integrity. Figure 55: Encapsulation Using Accessors and Mutators 5. Encapsulation Using Properties Properties provide a more elegant way to achieve encapsulation. In many programming languages, properties allow you to define accessors and mutators while simplifying their usage. 80 | P a g e Figure 56: Encapsulation Using Properties In conclusion, encapsulation is a fundamental concept in object-oriented programming that ensures data security, abstraction, and flexibility. When applied to an ADT, it enhances data protection and simplifies interactions with the ADT's interface. Properties, including Read-only and Write-only properties, are powerful tools for achieving encapsulation and information hiding in an elegant and organized manner. 81 | P a g e D2 Discuss the view that imperative ADTs are a basis for object orientation and, with justification, state whether you agree. In this section, we will explore the perspective that imperative Abstract Data Types (ADTs) form the foundation for object-oriented programming (OOP) and provide a comprehensive analysis of this viewpoint. We will then express our perspective on whether we agree or disagree with this perspective. 1. Imperative ADTs and Object Orientation Imperative ADTs represent data structures that encapsulate data and the operations that can be performed on that data, following an imperative programming paradigm. On the other hand, Object- Oriented Programming (OOP) is a paradigm that models real-world entities as objects, encapsulating data and behavior within those objects. 2. Integrating Imperative ADTs into an Object-Oriented Paradigm Imperative ADTs can be integrated into an object-oriented paradigm in several ways: Encapsulation: In OOP, objects encapsulate both data and behavior. Imperative ADTs can be translated into classes where data becomes object attributes (fields) and operations become methods. For example, a stack ADT with push and pop operations can be implemented as a Stack class with push() and pop() methods. Inheritance: OOP allows for the creation of new classes by inheriting attributes and methods from existing classes. Imperative ADTs can serve as base classes for OOP-based ADTs, providing a foundation for more specialized data structures. Polymorphism: Polymorphism in OOP enables objects of different classes to be treated as instances of a common superclass. Imperative ADTs can be integrated into a polymorphic hierarchy, allowing various data structures to share a common interface and be used interchangeably. 82 | P a g e 5. Example to prove the viewpoint Let's provide an example to illustrate the viewpoint that imperative Abstract Data Types (ADTs) can serve as a basis for object orientation. 5.1 Imperative ADT - Stack Functions: Figure 57: Imperative ADT 85 | P a g e 5.2 OOP-based ADT - Stack Class: Figure 58: Imperative OOP In the StackFunctions version, I’m using a static context to work with a stack, which is a typical approach in procedural or imperative programming. On the other hand, in the OopBaseADT class version, I define a OopBaseADT object that has attributes and methods, showcasing encapsulation and the principles of OOP. This transition highlights the foundational bridge between the concepts of imperative ADTs and object-oriented design. In conclusion, imperative ADTs indeed contribute to the foundations of object orientation by emphasizing encapsulation and data abstraction. However, OOP extends and refines these principles through the introduction of advanced features and a more holistic approach to software modeling. Imperative ADTs can be seen as a transitional step toward OOP, providing a stepping stone to a broader scope of object orientation. 86 | P a g e III. Evaluation Assignment Evaluation Summary P1 - Design Specification for Data Structures: Understanding: I demonstrated a clear understanding of abstract data types and their operations. Implementation: I successfully explained valid operations on data structures. Usability: I provided a solid foundation for comprehending abstract data types. P2 - Memory Stack and Function Calls: Understanding: I effectively explained the operations of a memory stack and its role in function calls. Implementation: I provided a clear explanation. Usability: I demonstrated practical knowledge of stack implementation in function calls. M1 - Concrete Data Structure for FIFO Queue: Understanding: I illustrated a concrete FIFO queue data structure. Implementation: I presented a relevant example. Usability: I provided a practical understanding of FIFO queues. M2 - Comparison of Sorting Algorithms: Understanding: I analyzed and compared the performance of sorting algorithms. Implementation: I explained the strengths and weaknesses of different algorithms. Usability: I offered insights into algorithm selection for specific scenarios. D1 - Analysis of Network Shortest Path Algorithms: Understanding: I analyzed network shortest path algorithms and provided examples. Implementation: I demonstrated comprehension through illustrations. 87 | P a g e In conclusion, through this report, I have endeavored to provide a comprehensive foundation for understanding and harnessing the power of abstract data types in the realm of software development. Together, we embark on a journey to explore the intricacies of ADTs, recognizing their transformative potential in shaping the future of software engineering. As I move forward in my role as a software developer and continue to explore the evolving software development landscape, the principles of ADTs will remain an invaluable tool in my arsenal, enabling innovation and efficiency in every project I undertake. V. References Source code: https://github.com/PhanTuanManh/Java.git 90 | P a g e Slide: https://docs.google.com/presentation/d/1DcIxED-3oYfu1mBYJfag1Xbr4cGAoHWQ/edit? usp=sharing&ouid=116355487917524966065&rtpof=true&sd=true Abstract data type in data structure - javatpoint (no date) www.javatpoint.com. Available at: https://www.javatpoint.com/abstract-data-type-in-data-structure (Accessed: 08 October 2023). Introduction to stack - data structure and algorithm tutorials (2023) GeeksforGeeks. Available at: https://www.geeksforgeeks.org/introduction-to-stack-data-structure-and-algorithm-tutorials/ (Accessed: 08 October 2023). Matthew Martin and Martin, M. (2023) Stack vs heap memory – difference between them, Guru99. Available at: https://www.guru99.com/stack-vs-heap.html (Accessed: 08 October 2023). Memory Stack Organization in computer architecture (2023) GeeksforGeeks. Available at: https://www.geeksforgeeks.org/memory-stack-organization-in-computer-architecture/ (Accessed: 08 October 2023). Queue Data Structure (2023) GeeksforGeeks. Available at: https://www.geeksforgeeks.org/queue-data- structure/ (Accessed: 08 October 2023). Sorting algorithms (2023) GeeksforGeeks. Available at: https://www.geeksforgeeks.org/sorting- algorithms/ (Accessed: 09 October 2023). Bubble sort - data structure and algorithm tutorials (2023) GeeksforGeeks. Available at: https://www.geeksforgeeks.org/bubble-sort/ (Accessed: 09 October 2023). Shortest path algorithm in Computer Network (no date) Online Courses and eBooks Library. Available at: https://www.tutorialspoint.com/shortest-path-algorithm-in-computer-network (Accessed: 09 October 2023). What is Dijkstra’s algorithm?: Introduction to dijkstra’s shortest path algorithm (2023) GeeksforGeeks. Available at: https://www.geeksforgeeks.org/introduction-to-dijkstras-shortest-path-algorithm/ (Accessed: 09 October 2023). Bellman Ford’s algorithm (no date) Programiz. Available at: https://www.programiz.com/dsa/bellman- ford-algorithm (Accessed: 09 October 2023). Algorithms 10: Abstract data types – stack (no date) Sign in or register. Available at: https://learn1.open.ac.uk/mod/oublog/viewpost.php?post=162582 (Accessed: 09 October 2023). What is encapsulation? (no date) Coursera. Available at: https://www.coursera.org/articles/encapsulation (Accessed: 09 October 2023). Bhakti (2019) Difference between data hiding and encapsulation (with comparison chart), Tech Differences. Available at: https://techdifferences.com/difference-between-data-hiding-and- encapsulation.html#Definition (Accessed: 09 October 2023). 91 | P a g e 92 | P a g e
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved