DSA Report
DSA Report
Activity 1 .........................................................................................................................................................................5
1.1 Introduction to data structure ........................................................................................................................5
1.1.1 Advantages of data structure .................................................................................................................5
1.1.2 Disadvantages of Data Structure ............................................................................................................6
1.2 What is a Stack? ..............................................................................................................................................7
1.2.1 Determine how the function of a memory store is used to execute function calls on a computer. .....8
1.3 What is First in First out (FIFO) .......................................................................................................................9
1.3.1 Illustrate, with an example, a concrete data structure for a First in First out (FIFO) queue. .............. 10
1.4 Compare the performance of two sorting algorithms. ................................................................................ 13
1.4.1 Quick sort Algorithm ............................................................................................................................ 13
1.4.2 Quicksort Example ............................................................................................................................... 14
1.4.3 Advantages of Quick Sort ..................................................................................................................... 15
1.4.4 Disadvantages of Quick Sort................................................................................................................. 16
1.5 Bubble sort Algorithm .................................................................................................................................. 16
1.5.1 Bubble sort Example ............................................................................................................................ 16
1.5.2 Advantages........................................................................................................................................... 19
1.5.3 Disadvantages ...................................................................................................................................... 19
1.6 Comparison .................................................................................................................................................. 19
1.7 Analyze the operation, using illustrations, of two network shortest path algorithms, providing an
example of each. ...................................................................................................................................................... 20
1.7.1 Dijkstra's Algorithm .............................................................................................................................. 20
1.7.2 Operation ............................................................................................................................................. 20
1.8 Bellman-Ford Algorithm ............................................................................................................................... 21
1.9 Most Suitable Data Structure for XYZ Pvt Ltd............................................................................................... 23
1.10 Why are specialized data structures not suitable for a bus allocation system?................................... 24
2 Activity 2............................................................................................................................................................... 26
2.1 Implement the java program for the Bus Reservation system..................................................................... 26
2.2 Output for system function worked. ............................................................................................................ 36
2.3 Introduction to error handling ..................................................................................................................... 39
2.3.1 Syntax error .......................................................................................................................................... 39
2.3.2 Runtime errors ..................................................................................................................................... 40
2.3.3 Logic errors........................................................................................................................................... 41
2.4 Appropriate error handling for the system .................................................................................................. 42
2.4.1 Exception Handling ............................................................................................................................... 42
2.4.2 Register a New Bus............................................................................................................................... 42
2.4.3 Register a New Customer ..................................................................................................................... 43
2.4.4 Reserve a Seat ...................................................................................................................................... 44
2.5 Introduction to check and arrange. .............................................................................................................. 44
2.5.1 Introduction to the Bus Reservation System........................................................................................ 44
2.5.2 Introduction to check case. .................................................................................................................. 47
2.5.3 Test case for CMD ................................................................................................................................ 49
2.5.4 Test case for compiling the program.................................................................................................... 51
2.5.5 Test case for Bus Reservation menu .................................................................................................... 51
2.5.6 Test case for Customer Registration .................................................................................................... 52
2.5.7 Test case for Register Bus..................................................................................................................... 53
2.5.8 Test case for Search Buses ................................................................................................................... 54
2.5.9 Test case for Reserve Seat.................................................................................................................... 55
2.5.10 Test case for Cancel Reservation .......................................................................................................... 56
2.5.11 Test case for Request New Seat ........................................................................................................... 58
2.5.12 Test case for Display Reservations ....................................................................................................... 59
2.5.13 Test case for Customer or Bus Not Found............................................................................................ 60
2.6 Examine the advantages of encapsulation and information hiding when using an ADT. ...................... 61
3 Activity 3............................................................................................................................................................... 63
3.1 Buses and Customer Registration details square measure keeps from the latest to oldest. ...................... 63
3.2 Create main class for bus Reservation system. ............................................................................................ 65
3.3 Introduction to ADT...................................................................................................................................... 66
3.4 Stack abstract information sort (ADT) .......................................................................................................... 67
3.4.1 Advantages and disadvantage of Stack abstract information sort (ADT) ............................................ 69
3.4.2 Disadvantages of Stack ADT ................................................................................................................. 69
3.5 Queue abstract information sort (ADT)........................................................................................................ 70
3.6 Introduction to OOP ..................................................................................................................................... 71
3.7 Use of Encapsulation for the situation ......................................................................................................... 73
3.7.1 Data Protection .................................................................................................................................... 73
3.7.2 Access Control ...................................................................................................................................... 73
3.7.3 Flexibility and Maintenance ................................................................................................................. 73
3.7.4 Code Organization ............................................................................................................................... 74
3.8 Blessings of Encapsulation and knowledge activity ..................................................................................... 76
3.8.1 Benefits of Encapsulation .................................................................................................................... 76
3.8.2 Knowledge Activity ............................................................................................................................... 76
3.9 Imperative Abstract knowledge sorts of area unit the premise for object orientation........................ 77
3.10 Demonstrate how the implementation of an ADT/algorithm solves a well-defined problem. ................. 78
3.10.1 Customer and Bus Data Storage .......................................................................................................... 78
3.10.2 Searching for Available Buses............................................................................................................... 78
3.10.3 Reserving a Seat ................................................................................................................................... 79
3.10.4 Cancelling a Reservation ...................................................................................................................... 80
3.10.5 Adding to the Waiting List .................................................................................................................... 80
3.10.6 Displaying Reservations ....................................................................................................................... 81
4 Activity 4............................................................................................................................................................... 82
4.1.1. Type of graph ............................................................................................................................................... 82
4.2. Introduction to shortest path algorithms......................................................................................................... 85
4.1 Dijkstra’s Algorithm ...................................................................................................................................... 87
4.2 Bellman-Ford Algorithm ............................................................................................................................... 87
4.3 Floyd-Warshall Algorithm............................................................................................................................. 87
4.4 Johnson’s Algorithm ..................................................................................................................................... 88
4.3. Choosing the shortest path formula for the state of affairs ............................................................................ 88
1. First-Come-First Serve (FCFS) ........................................................................................................................... 88
2. Dijkstra's Algorithm .......................................................................................................................................... 90
3. Bellman-Ford .................................................................................................................................................... 92
4.3.1. Illustration of the operation for Dijkstra’s formula ...................................................................................... 93
4.3.2. Illustration the operation for First-Come-First-Serve Algorithm ................................................................ 101
4.5 Initialization ................................................................................................................................................ 101
4.6 Customer Reservation Requests ................................................................................................................ 102
4.7 Reservation Order ...................................................................................................................................... 102
4.8 Seat Allocation ........................................................................................................................................... 102
4.9 Notification ................................................................................................................................................. 103
4.10 Queue for Waiting Customers.................................................................................................................... 103
4.11 Waitlist Queue ........................................................................................................................................... 103
4.12 Cancellation ................................................................................................................................................ 103
4.13 Seat Allocation from Waiting List ............................................................................................................... 103
4.4. What is sorting algorithms? ........................................................................................................................... 107
4.5. Illustration sorting algorithm supports bus id with 2 other methods. ........................................................... 111
4.14 the QuickSort algorithm ............................................................................................................................. 111
4.15 Merge Sort algorithm ................................................................................................................................. 115
References ................................................................................................................................................................. 119
Activity 1
1.1 Introduction to data structure
Imagine creating a hugely successful app with a user base that is rapidly approaching one million.
(Congrats!) Although consumers adore the app, many are expressing frustration that it is getting increasingly
sluggish, to the point that some users are beginning to stop using it. Your app now scans through an unsorted
list of Python dictionaries until it gets the required user ID, which you observe is the biggest bottleneck in
the process of retrieving user information after authentication.
You curse your 3 a.m. self for writing that code and try to figure out how to repair it. How can we store user
IDs to make it as quick as possible to access any ID? The list might be sorted,
Newer clients with high-numbered IDs, however, will require hundreds of thousands of steps to authenticate
if we search from scratch each time. The clients who have been with us from the beginning would be
penalized if we started the search at the bottom of the list.
You realize that organizing user data into a binary search tree is a preferable strategy since it would enable
us to locate any of our million IDs, on average, in just twenty steps. In fact, databases use a variation of this
data structure to index records for blazing-fast retrieval. Your app's latency decreases as a result of quietly
transferring user information to a database, everyone is pleased, and you promise to keep quiet about how
you initially stored the data. (Sosna, 2021)
- Additionally, data structures help us efficiently store data on circles so that we can retrieve the data
later.
- Data structures, as we've seen, are a way to organize data into a predetermined form. At the moment,
the sort of data structure utilized affects how quickly a program runs.
- We can reuse data thanks to data structures. Organizations, we can produce a few data sets and store
them in libraries for usage by multiple customers.
- Charts are data structures that enable us to interact with, visualize, and model real-world problems.
- We can examine, use, and interact with hierarchical data sets using trees as data structures. For
instance, the buyer could browse through b, which is frequently utilized while seeking related areas, after
looking through a.
- Data structures offer data deliberation, so the client is free from worrying about how the data is stored
in the framework.
- Different programming languages come with data structures that include implicit capabilities (or
techniques) that let us use the database more effectively.
- The program's efficiency while dealing with huge data sets is greatly influenced by the choice of data
structure. Therefore, selecting a proper data structure is essential. (.javatpoint.com, 2023)
- Complexity: Some data structures, such as advanced trees and graphs, can be complex to implement
and understand. This complexity can make code harder to maintain and debug.
- Another software developer finds a small portion of the data structures challenging to work with.
- Certain data structures offer delayed data access due to their complex design.
- We may anticipate specialists to handle the situation if challenging issues or challenges develop.
- Applications that use data structures require highly qualified, competent resources to handle the tasks
related to the data structure. Think about the cluster concept we covered before. If we want to obtain the
elements of the aforementioned show in ascending or descending order, we need be familiar with calculations
used in arrangement techniques such as addition sort, bubble sort, and so forth. However, a smart coder may
organise their organizing calculation. There may also be other complex procedures to be followed, which
will call for the participation of dedicated specialists.
- Planning data structures without prior planning is very challenging and may need complex
calculations, a lot of work, and tests (quality testing).
- The center of a chart is made up of an exhibit or a rundown, much like larger programmes require
data structures within each other. As a result, maintenance in such circumstances is both difficult and
expensive.
- To make sure that your data structure is finished and prepared for hierarchical purposes, it may
require complex calculations, a lot of work, and testing. Costs will rise as a result of this. Additionally, it's
possible to find that the newly built data structure isn't as effective as anticipated once work is finished.
(.javatpoint.com, 2023)
The base of the stack is important because objects that are kept there and are located there closer to the base
are those that have been there the longest. The one that should be taken out first is the one that was just
introduced. Last-in, first-out, or LIFO, is another name for this ordering concept. It offers an ordering
determined by how long the item has been in the collection. The upper things are more recent, while the
bottom items are more vintage.
Everyday life has several stack examples. Most cafeterias have a stack of trays or plates, and you take the
one at the top to reveal a fresh tray or plate for the person in queue behind you. Figure 1 depicts a desk with
a stack of books on it. The top book is the only one whose cover is clearly seen. We have to get rid of the
ones that are on top of them so we can reach the others in the stack. Another stack may be seen in Figure 2.
Many simple Python data objects may be found in this one. (runestone.academy, 2023)
1.2.1 Determine how the function of a memory store is used to execute function calls on a computer.
Function Declaration
Before a function can be called, it must be declared or defined in the program. This declaration typically
includes the function's name, return type, parameter list, and the code block that defines its behavior.
Memory Allocation
When the program is compiled or interpreted, memory space is allocated for variables, including functions.
This memory allocation includes a specific location in memory for each function. The function's code and
data are stored in this memory location.
Function Call
a. Pushing Data
- Any arguments or parameters passed to the function are pushed onto the program's call stack.
The call stack is a specific region of memory used to manage function calls.
b. Jump to Function
- The program's execution flow jumps to the memory location where the function's code is
stored. This is known as the function's entry point.
c. Function Execution
- The function's code is executed. Any local variables defined within the function are allocated
memory on the call stack.
d. Return Address
- The address of the next instruction in the calling function is usually saved on the call stack as a return
address. This allows the program to know where to resume execution after the function call is complete.
d. Return Value
- If the function has a return type other than "void," it computes a return value. This value is
stored in a designated memory location.
e. Function Cleanup
- After the function has finished executing, it may deallocate memory for local variables, and it may
release any resources it has acquired (e.g., closing files, releasing memory).
Returning to Caller
Once the function has completed its execution, control returns to the calling function. This is achieved by
popping the return address from the call stack.
If the calling function expects a return value, it can access the memory location where the return value is
stored and use it in further computations or assignments.
Memory Deallocation
As functions return and local variables go out of scope, memory allocated for these variables is deallocated
to ensure efficient memory usage. (geeksforgeeks, 2023)
In the provided example, a FIFO queue is implemented using a linked list data structure. A linked list consists
of nodes, where each node holds data and a reference to the next node. This linked list structure allows for
efficient insertions and removals at both ends of the queue:
- The enqueue operation adds elements to the rear of the queue, and the newly added element becomes
the last in line.
- The dequeue operation removes elements from the front of the queue, ensuring that the oldest element
is processed first.
- The peek operation allows you to view the front element without removing it.
- The Empty method checks if the queue has no elements, indicating that it's empty.
Now, let's illustrate how to use this FIFO Queue class with a simple example.
Figure 5 this FIFO Queue class with a simple example. Author developer
The peek method allows viewing the front element without removing it from the queue. This is
useful when you want to inspect the next item in line without actually dequeuing it.
After dequeuing all the elements, the code checks whether the queue is empty using the isEmpty method,
which returns true if the queue has no elements.
This example illustrates the core functionality of a FIFO queue, where elements are processed in
the order they were added, making it suitable for scenarios like task scheduling or event handling.
(schools, 2023)
1.4 Compare the performance of two sorting algorithms.
To compare the performance of two sorting algorithms, we typically consider factors like time
complexity, space complexity, and how their performance scales with the size of the input data. In
this comparison, let's look at two widely used sorting algorithms: Quicksort and Bubblesort.
Time Complexity- Quicksort has an average and best-case time complexity of O(n*log(n)), which
makes it one of the fastest sorting algorithms available. However, in the worst-case scenario, it can
degrade to O(n^2) if the pivot selection is poor (e.g., always selecting the smallest or largest
element).
Space Complexity- Quicksort is an in-place sorting algorithm, which means it doesn't require
additional memory proportional to the size of the input array.
Performance Characteristics- Quicksort is known for its efficiency in practice, especially when
implemented well. It's often faster than most other sorting algorithms and works well with large
datasets. Its performance is influenced by factors such as pivot selection and the state of the input
data.
1.4.2 Quicksort Example
I. The quick Sort method is a recursive function for sorting an array using the Quicksort
algorithm. It takes three parameters: the array to be sorted (arr), the index of the low (left)
boundary (low), and the index of the high (right) boundary (high) of the subarray to be
sorted.
II. Inside quick Sort, it checks if low is less than high, which means there are elements to sort.
If the base case is not met, it proceeds with the sorting.
III. The partition method is a helper function used by quick Sort to partition the array into two
subarrays around a pivot element. It takes the array (arr), the index of the low boundary
(low), and the index of the high boundary (high).
IV. Within partition, it selects the pivot element as the last element of the subarray (in this case,
arr[high]). It then rearranges the elements in the subarray so that all elements less than the
pivot are on the left, and all elements greater are on the right. This is done using the i and
j pointers to track the elements.
V. The i pointer moves to the right when an element is found that is less than the pivot. When
this happens, it swaps the element at i with the element at j. This process continues until
all elements are partitioned properly.
VI. After the loop, the pivot element is moved to its correct position by swapping it with the
element at i + 1. This effectively places the pivot in the middle of the two subarrays.
VIII. In the main method, an example array arr is defined and printed to the console.
IX. The quick Sort method is called to sort the entire array, and then the sorted array is printed
to the console. (W3schools, 2023)
- The worst-case temporal complexity, which happens when the pivot is badly chosen, is
O(N2).
- Small data sets are not a good fit for it.
- It is not a stable sort, which means that in the event of a rapid sort, if two items have the
same key, their relative order will not be retained in the sorted output. (.geeksforgeeks,
2023)
Time Complexity- Bubblesort has a worst-case time complexity of O(n^2), which makes it one of
the slowest sorting algorithms, especially for large datasets. It repeatedly compares and swaps
adjacent elements until the entire array is sorted.
Space Complexity- Bubblesort is an in-place sorting algorithm and doesn't require additional
memory proportional to the size of the input array.
Performance Characteristics- Bubblesort is not typically used for large datasets due to its poor time
complexity, especially in the worst-case scenario. It's mainly used for educational purposes or for
small datasets where simplicity is more important than efficiency.
1.5.1 Bubble sort Example
Here's a Java example using the Bubblesort algorithm to sort an array of integers:
I. public static void bubble Sort(int[] arr): This method takes an array of integers as a
parameter and sorts it using the Bubble Sort algorithm.
II. int n = arr.length: It calculates the length of the array, which is the number of elements to
be sorted.
III. The code uses two nested for loops to iterate through the array. The outer loop (for (int i
= 0; i < n - 1; i++)) runs from the first element to the second-to-last element. It represents
the pass through the array. With each pass, the largest element "bubbles up" to its correct position
at the end.
IV. The inner loop (for (int j = 0; j < n - i - 1; j++)) runs within each pass. It compares adjacent
elements (arr[j] and arr[j + 1]) and swaps them if they are in the wrong order (i.e., if arr[j]
is greater than arr[j + 1]).
V. if (arr[j] > arr [j + 1]): This condition checks if the current element is greater than the next
element.
VI. If the condition is true, a temporary variable temp is used to swap the values of arr[j] and
arr[j + 1], effectively moving the larger element to the right.
VII. This process continues for each pass through the array, gradually sorting the elements from
the end to the beginning.
VIII. In the main method, an unsorted array of integers is created, and its original state is
printed.
X. Finally, the sorted array is printed, showing the elements in ascending order. (W3schools,
2023)
1.5.2 Advantages
- Simple to comprehend.
- Simple to use.
- No additional memory is required; in-place.
- when the array is almost sorted, performs very well.
1.5.3 Disadvantages
1.6 Comparison
- Quicksort is significantly faster than Bubblesort, especially for larger datasets. Its
average-case and best-case time complexity of O(n*log(n)) leads to efficient sorting.
- Bubblesort is much slower and is less efficient, having a worst-case time complexity of
O(n^2).
- Quicksort is an in-place sorting algorithm, meaning it doesn't require extra memory for
sorting. Bubblesort shares this property, so they are similar in terms of space complexity.
- In practice, Quicksort is widely used and efficient. Bubblesort is not recommended for
real-world applications due to its poor performance with larger datasets.
In summary, the choice between these two sorting algorithms depends on the specific requirements
of your task. For large datasets or real-world applications where efficiency is important, Quicksort
is a better choice. Bubblesort is mainly useful for educational purposes or for small datasets where
its simplicity can outweigh its inefficiency.
1.7 Analyze the operation, using illustrations, of two network shortest path algorithms,
providing an example of each.
1.7.1 Dijkstra's Algorithm
Dijkstra's algorithm is used to find the shortest path from a source node to all other nodes in a
weighted graph. It works by iteratively selecting the node with the smallest tentative distance from
the source and relaxing the distances of its neighboring nodes. (geeksforgeeks.org, 2023)
1.7.2 Operation
- Initialize the distances from the source node to all other nodes with infinity, except the
distance from the source to itself (which is set to 0).
- Mark all nodes as unvisited.
- Select the unvisited node with the smallest tentative distance from the source. In the first
iteration, this will be the source node itself.
- For the selected node, calculate the tentative distance to its neighbors through the current
node and update their distances if they are smaller than the current values.
- Mark the selected node as visited.
- Repeat steps 3 to 5 until all nodes have been visited or the destination node has been
reached.
Example
Let's consider a simple graph and find the shortest path from node A to all other nodes using
Dijkstra's algorithm.
Figure 8 Dijkstra's Algorithm Author developer
Starting from node A, Dijkstra's algorithm would first visit B, then E, and finally C and F.
The Bellman-Ford algorithm is used to find the shortest path from a source node to all other nodes
in a weighted graph, including graphs with negative-weight edges. It iteratively relaxes the
distances to all nodes and is capable of detecting negative weight cycles.
Operation
Initialize the distances from the source node to all other nodes with infinity, except the distance
from the source to itself (which is set to 0).
Iterate through all edges in the graph V-1 times (where V is the number of nodes).
For each edge (u, v) in the graph, update the distance to node v if it is shorter through node u.
Continue iterating through the edges until no further updates are possible.
Example
Consider a graph with negative-weight edges and find the shortest path from node A to all other
nodes using the Bellman-Ford algorithm.
In the example, Bellman-Ford correctly detects a negative-weight cycle and assigns a distance of
negative infinity to the nodes affected by the cycle, preventing infinite loops in path calculations.
1.9 Most Suitable Data Structure for XYZ Pvt Ltd
Customer Information
- For storing customer information, a class or structure is appropriate. You might use a
custom class, such as Customer, to store customer details like name, mobile number, email,
city, and age. This class can be organized into an array or a list to manage multiple
customers.
Bus Information
- Similar to customer information, a custom class or structure (e.g., Bus) can be used to store
details about each bus, including the bus number, total seats, starting point, ending point,
starting time, and fare. You can maintain a list or array of buses.
Reservations
- Reservations can be stored in a data structure such as a list or database table. Each
reservation can be represented by a custom class, such as Reservation, which contains the
customer, bus, reservation date, and status (confirmed, canceled, waiting). A list or
database table allows you to manage and search reservations efficiently.
Seat Availability
- To manage seat availability, you can use an array or a list within the Bus class to keep track
of which seats are available and which are booked. You might use a Boolean array, where
each index represents a seat, and true indicates a booked seat, while false indicates an
available seat.
Displaying Reservations
- To display reservations, you can use data structures to organize and format the reservation
data. For example, you can create a list of reservations and format it for display in the user
interface.
1.10 Why are specialized data structures not suitable for a bus allocation system?
Custom Classes for Customers and Buses
- Using other data structures like arrays or simple lists to store customer and bus information
may lack structure and make it challenging to manage and search for specific customer or
bus details.
- Storing reservations in less structured data structures like arrays or simple lists can make
it difficult to efficiently search for specific reservations, sort them by criteria like date, or
maintain data integrity.
- Other data structures like linked lists or sets are not as efficient for representing seat
availability because they may require additional operations to find and update the status of
individual seats.
Queue for Seat Requests
- Using other data structures like stacks or unordered lists would not maintain the desired
order of seat requests.
Displaying Reservations
- If you use complex or inefficient data structures, it may lead to poor performance and a
less user-friendly experience.
2 Activity 2
2.1 Implement the java program for the Bus Reservation system.
Figure 24 represents the option to search for available buses between two points.
Figure 25 represents the option to reserve a seat for a customer on a bus.
Basically, in a java program can occur some errors that are divided into three types:
1. Syntax error
2. Runtime errors
3. Logic errors
Some of the most typical sorts of Java issues that programmers go through include syntax or
compilation errors. The Java compiler is unable to transform the code into a machine-readable
format when these errors take place because the code disobeys the syntactic rules of the Java
language. (codingninjas.com, 2023)
Examples of Java code that might have syntactic or compilation issues are shown below:
While the program is being executed, run time mistakes take place or, to put it another way, are
found. When a user submits inaccurate or irrelevant data, they are occasionally identified. When
a program asks the computer to do an action that it is not capable of reliably performing but does
not contain any syntax mistakes, runtime errors arise. These problems cannot be found by the
compiler during compilation because it lacks the necessary tools. While the application is
executing, the JVM (Java Virtual Machine) notices it. Our error code may be contained inside the
try block, and the error can be caught inside the catch block, to handle the error during run time.
(Sonal_singh, 2022)
A logic error occurs when your software compiles and runs, but performs the incorrect thing,
provides an inaccurate result, or produces nothing when it should. Neither the compiler nor the
JVM can identify these mistakes. Because the Java system doesn't understand what your
application is meant to perform, it offers no further details to aid in the detection of errors.
Semantic mistakes are a another name for logical errors. These problems occur because a
programmer employed an improper notion or concept when writing the code. Grammar faults are
known as syntax errors, whereas logical errors are errors that result from a wrong interpretation.
(Sonal_singh, 2022)
- This change makes the program incorrectly confirm reservations without checking seat
availability.
Appropriate error handling is crucial for ensuring that a software system can gracefully handle
unexpected situations and provide useful feedback to users. Here are some ways to enhance error
handling in the provided code for the bus reservation system
2.4.1 Exception Handling
Use try-catch blocks to catch exceptions and handle errors gracefully. For example, if the program
attempts to read an integer, you should catch InputMismatchException if the user enters a non-
integer value.
Example
- The code prompts the user to enter bus details, including the bus number, total seats,
starting point, ending point, starting time, and fare.
- Nested try-catch blocks are used to handle both the total seats (an integer) and the fare (a
double) inputs.
- If the user enters invalid values, appropriate InputMismatchException catch blocks
handle each case, print error messages, and clear the input buffer.
Figure 51 error handling. Registering a new bus
- A try-catch block is used to handle the age input, which must be an integer. If the user
enters an invalid value (e.g., not an integer), it catches the InputMismatchException, prints
an error message, and clears the input buffer.
- The code prompts the user to enter a customer ID and a bus ID to reserve a seat.
- Try-catch blocks are used to handle both the customer ID and bus ID inputs. If the user
enters invalid values, catch blocks for InputMismatchException handle each case, print
error messages, and clear the input buffer.
The provided Java code represents a simple Bus Reservation System. This system allows users to
register customers and buses, search for available buses, make reservations, cancel reservations,
and request seats to be added to a waiting list. It maintains information about customers, buses,
and reservations and provides a menu-driven interface for users to interact with the system.
Key features of the system include customer and bus registration, searching for available buses
between two points, seat reservations, cancellation of reservations, and the management of waiting
list requests. The code demonstrates the basic structure of a bus reservation system in a text-based
interface.
To ensure its robustness and usability, you may consider implementing error handling, data
validation, code organization, and improving the user experience as outlined in the previous
response.
ID: 3 option:3 Bus Search Search for a Bus ID Bus details are Pass
bus by ID. displayed.
ID: 7 option:3 Search Search for Starting and List of available buses Pass
Available available ending points is displayed.
Buses buses
between
two points.
ID: 8 option:7 Invalid Search for Invalid points No buses found, Pass
Point buses with appropriate message
Search invalid displayed.
points.
In a case study, you must assess a particular circumstance and explain how its many components
connect to theory. The case can refer to a real-life or fictitious topic, organization, person, or group
of individuals. You may be required to create issues with remedies or suggestions for future action
depending on your job.
The primary purpose of a test case is to validate that the software performs correctly and
consistently under different scenarios. Each test case is constructed to examine a particular
functionality, feature, or use case within the software. It specifies the inputs to be used, the
expected results, and the steps to be taken to execute the test. (.monash.edu, 2023)
TC 1 Open the Bus Start the application Click on the application icon Bus Reservation
Reservation System opens
System successfully
TC 3 Customer Select "Register Enter customer details: Name: John Customer
Registration Customer" Doe Mobile Number: 123-456- registered
7890 Email, City: New York Age: successfully
30
TC 4 Bus Registration Select "Register Bus" Enter bus details: Bus Number: Bus registered
XYZ123 Total Seats: 50 Starting successfully
Point: New York Ending Point: Los
Angeles Starting Time: 08:00 AM
Fare: $50.00
TC 5 Search for Select "Search Buses" Enter starting point: New York List of available
Available Buses Ending point: Los Angeles buses displayed
TC 6 Reserve a Seat Select "Reserve Seat" Enter customer ID: [valid customer Seat reserved
ID] Enter bus ID: [valid bus ID] successfully
Enter reservation date: [valid date]
TC 8 Request a New Select "Request New Enter customer ID: [valid customer Request added to
Seat (Waiting Seat" ID] Enter bus ID: [valid bus ID] the waiting list
List) Enter reservation date: [valid date]
successfully
TC 10 Search for Invalid Select "Search Buses" Enter starting point: [non-existent No buses found,
Buses point] Enter ending point: [non- appropriate
existent point] message displayed
Test ID 01
Test scenario Open command prompt
Test purpose Run the java file via the command prompt
Test steps Run command prompt
Test data VS code right click on the java file then select cmd folder
Expected result CMD opened successfully
Actual result CMD opened successfully
Test status Pass/Fail Pass
Conclusion Command prompt opened successfully
Table 3 Test case for Open command prompt
Figure 54 Test case for Open command prompt
Test ID 02
Test scenario Compile the program
Test purpose Convert the java file into the machine language
Test steps Enter the cmd command “javac filename.java” to compile the
program
Test data The java file gets translated into the class file
Expected result Java file compiled successfully
Actual result Java file compiled successfully
Test status Pass/Fail Pass
Conclusion Java file was compiled successfully
Table 4 Test case for Compile the program.
Test ID 03
Test scenario Open Bus Reservation menu and check operations
Test purpose Select the option for user need
Test steps Enter the any option from window as guide
Test data Type the operations one by one
Expected result Menu and operations worked successfully
Actual result Menu and operations worked successfully
Test status Pass/Fail Pass
Conclusion Menu and operations are worked successfully
Table 5 Test case for Open Bus Reservation menu
Test ID 04
Test scenario Customer Registration
Test purpose To verify the process of registering a customer in the Bus
Reservation System.
Expected result The system should successfully register the customer with the
provided information.
Test ID 05
Test scenario Register Bus
Test purpose
To verify the process of registering a new bus in the Bus
Reservation System.
Test steps Launch the Bus Reservation System.
Access the "Register Bus" feature.
Fill in the bus details, including bus number, total seats, starting
point, ending point, starting time, and fare.
Submit the registration form.
Test data
Bus Number: BUS123
Total Seats: 50
Starting Point: A
Ending Point: B
Starting Time: 10:00 AM
Fare: $30.00
Expected result The system should successfully register the bus with the provided
information.
Actual result The bus is registered successfully.
Test status Pass/Fail Pass
Conclusion Bus registration functionality is working as expected in the Bus
Reservation System. Bus number BUS123, with the provided
details, has been successfully registered.
Table 7 Test case for Register Bus
Test ID 06
Test scenario Search Buses
Test purpose To verify the process of searching for available buses between two
specified points in the Bus Reservation System.
Test steps Launch the Bus Reservation System.
Access the "Search Buses" feature.
Enter the starting point and ending point for the desired route.
Initiate the search.
Actual result The system displays a list of available buses between City A and
City B.
Test status Pass/Fail Pass
Conclusion The "Search Buses" functionality successfully retrieved and
displayed a list of buses operating between the specified starting
and ending points.
Table 8 Test case for Search Buses
Test ID 07
Test scenario Reserve Seat
Test purpose To verify the process of reserving a seat for a customer on a
specific bus in the Bus Reservation System.
Test steps Launch the Bus Reservation System.
Access the "Reserve Seat" feature.
Enter the Customer ID and Bus ID for the reservation. Input
the reservation date (in the format YYYY-MM-DD). Initiate
the seat reservation process.
Expected result The system should successfully reserve a seat for the customer on the
specified bus, and the status should be set to "confirmed."
Actual result The system confirms the reservation and sets the status to
"confirmed."
Test status Pass/Fail Pass
Conclusion The "Reserve Seat" functionality successfully reserves a seat for the
customer on the specified bus, and the status is set to "confirmed."
Test ID 08
Test scenario Cancel Reservation
Test purpose To verify the process of canceling an existing reservation in the
Bus Reservation System.
Test data Expected Result: The system should successfully cancel the
reservation, increase the total seats of the associated bus (if the
status was "confirmed"), and update the status to "canceled."
Expected result
Actual result The system confirms the cancellation, increases the available seats
of the associated bus (if applicable), and sets the status to
"canceled."
Reservation ID: [Provide a valid Reservation ID]
Test ID 09
Test scenario Request New Seat
Test purpose To verify the process of requesting a new seat in the Bus
Reservation System.
Expected result The system should successfully add the request for a new seat to
the waiting list.
Actual result The system confirms the addition of the new seat request to the
waiting list.
Test ID 10
Test scenario Display Reservations
Actual result The system displays the list of confirmed reservations as expected.
Test ID 11
Test scenario Customer or Bus Not Found
Expected result The system should provide a clear and user-friendly error message
indicating that the customer or bus was not found.
Actual result The system displays an error message confirming that the
customer or bus was not found.
Test status Pass/Fail Pass
Conclusion The system handles the scenario of a non-existent customer or bus
by displaying an appropriate error message.
2.6 Examine the advantages of encapsulation and information hiding when using an ADT.
1. Encapsulation for Customer, Bus, and Reservation Classes
In the Customer, Bus, and Reservation classes, private instance variables are used to encapsulate
data. For example, the customer's email, bus number, or reservation date are private attributes.
Public methods (getters and setters) are provided to control access to these private attributes. This
encapsulation ensures that the data can only be accessed and modified through defined methods,
maintaining data integrity.
2. Information Hiding for Customer, Bus, and Reservation Classes:
The internal implementation details of the Customer, Bus, and Reservation classes are hidden
from external users of the classes.
Users of these classes do not need to know how the ID, bus number, or reservation date is stored
or managed internally. They only interact with the public methods like getters and setters.
This information hiding simplifies the use of these classes, as users do not need to understand the complex
data management within the classes.
3. Error Prevention
Encapsulation and information hiding help prevent errors by restricting access to the internal state
of the classes. For example, customers cannot directly modify their IDs, reducing the risk of data
corruption.
4. Enhanced Collaboration
Encapsulation allows developers to work independently on different aspects of the system. They
can focus on the public interfaces of classes and use them without needing to know the internal
details.
3 Activity 3
3.1 Buses and Customer Registration details square measure keeps from the latest to oldest.
The statement "Buses and Customer Registration details square measure keeps from the latest to
oldest" seems to indicate that, in the system you're working with, the records of both buses and
customer registrations are sorted or stored in a way where the newest entries appear before the
older ones. In other words, the system maintains a chronological order with the most recent
registrations or bus information being stored at the top.
Without examining the entire system and its code, I can't provide a definitive answer. However,
it's common in many systems to sort and display records in descending order of creation time or
registration date, showing the latest entries first. This approach can be helpful when users need to
quickly access the most recent data.
- The purpose of this class is to represent and manage information about customers. Here's
a breakdown of the key components and the purpose they serve:
“displayReservations” method is to provide a clear and organized way to present information
about confirmed reservations within the Bus Reservation System.
These cases allow the user to interact with the system to add new customer and bus information,
expanding the system's database of registered customers and available buses. The user input is
crucial for the proper functioning of the reservation system, as it populates the system with
essential data for managing reservations and providing services to customers. The switch statement
is used to execute the appropriate actions based on the user's choice (1 for customer registration,
2 for bus registration).
Figure 69 Create User input function.
The kinds of values that a variable can hold are defined or categorized using data types. The
potential procedures that may be performed on such values are also described. An integer value,
for instance, can be stored using the integer data type. Addition, subtraction, multiplication, and
modulo are all operations that may be performed on an integer.
ADT stands for abstract data type, which is a notion or model of a data type. ADT eliminates the
need for users to worry about the implementation of a data type. The user will now have predefined
functions for every data type at their disposal for every action.
In ADT, a user often has knowledge of what to perform without divulging specific instructions.
These models are described in terms of the data they contain and the accompanying activities. We
implement ADTs using various techniques and logic in every programming language. The
accompanying operations described for that ADT can still be carried out regardless of language,
though. For instance, structure is mostly used to implement ADTs in C. They are implemented
using classes in C++ or Java, though. All languages have the same procedures, nevertheless.
(Datta, 2023)
3.4 Stack abstract information sort (ADT)
An Abstract Data Type (ADT) is a category of objects whose actions and value ranges are specified
by a set of rules. The definition of ADT does not specify how these operations are to be
implemented, simply what operations are to be done. It doesn't say how operations will be
implemented or what techniques will be utilised to save and retrieve data from memory. It's dubbed
"abstract" because it doesn't concern itself with specific implementation details.
Most computer languages make heavy use of ADTs, and one such example is the stack. The stack
gets its name from the fact that it may be used in the same ways as actual stacks of things like
playing cards, dishes, and so on. According to the LIFO (Last in - First out) principle, the
item that was most recently added to the stack would be the one to be removed first. All data
operations may be performed at the same end in a stack ADT. Only the item at the top of a stack
may be accessed at any one moment.
Stack (): This represents the constructor of a stack. It's used to initialize a new stack data
structure. In some programming languages, you might create a new stack using Stack ().
push(item): The push operation is used to add (or push) an item onto the top of the stack. This
item becomes the new top of the stack. It's a fundamental operation for building and using a
stack.
pop (): The pop operation is used to remove and return the item at the top of the stack. After
this operation, the item is removed from the stack, and the stack size decreases by one.
peek (): The peek operation allows you to view (or "peek" at) the item at the top of the stack
without removing it. It's a way to inspect the top element without modifying the stack's
contents.
isEmpty (): This method is used to check if the stack is empty. It returns true if the stack
contains no elements and false if there are one or more elements in the stack.
size (): The size method returns the number of elements currently in the stack. It provides the
count of items stored in the stack.
The following actions and structures describe the stack abstract data type.
The stack ADT may be realized as a pointer to the head of a singly linked list. It is possible to
implement a stack with a fixed size. Stack overflow occurs when an item is inserted into a
stack that is already at capacity. (geeksforgeeks, 2023)
- - Simplicity: Stacks are basic to get it and execute. They have a restricted set of operations,
which makes them simple to work with.
- - Efficiency: The thrust and pop operations for a stack have a time complexity of O(1),
which suggests they are exceptionally proficient. This makes stacks reasonable for certain
calculations and information administration
- assignments.
- - LIFO Rule: The Final In, To begin with Out (LIFO) guideline that stacks take after is
useful in scenarios where you would like to keep track of the foremost later things or work
calls. It's especially profitable in overseeing work call stacks.
- - Memory Administration: Stacks can be utilized for memory administration in a few
programming dialects. For case, they can be utilized to designate and deallocate memory
in a way that takes after the LIFO guideline.
- - Undo/Redo Usefulness: Stacks are commonly used to actualize fix and re-try usefulness
in applications. They permit you to return activities within the switch arrange in which they
were performed.
- Size Limitation: Stacks are often implemented with a fixed size, and when they are full,
pushing more elements can lead to a stack overflow. This limitation can be a problem in
some applications.
- Inefficient for Some Tasks: While stacks are efficient for specific tasks, they are inefficient
for others. For example, searching for an item in a stack is not efficient because you
typically have to pop elements until you find the one you're looking for.
- Lack of Random Access: Stacks do not support random access to elements. You can only
access the top element. If you need to access elements in arbitrary positions, a stack is not
the right data structure.
- Limited Real-world Analogies: While the LIFO principle has real-world analogies (e.g., a
stack of plates), not all scenarios can be easily mapped to a stack. This limitation can make
it challenging to decide when to use a stack in some applications.
-
In a queue, inserting and removing data are handled independently at opposite ends of the data
structure. The items of a queue are added or removed from the structure at two distinct points. At
one end, an insert is made, and at the other, a delete is made. The'rear' position in a queue data
structure is where new items are added, whereas the 'front' position is where old items are removed.
The FIFO (First In First Out) principle governs the order in which elements are added to or
removed from a queue data structure.
peek ()– Rather of deleting the element from the queue, return it if the queue is not empty. size
isEmpty () – If the queue is empty and you want to return a true value, do so. isFull
() – The queue is full if and only if you return true; otherwise, return false.
In object-oriented programming (OOP), data, rather than functions and logic, is the organizing
principle behind program structure. One definition of an object is a data field with its own set of
characteristics and quirks.
In OOP, developers' attention is on the objects they create, rather than the reasoning behind
creating those things. Large, sophisticated, and often updated or maintained programmers are ideal
candidates for this kind of programming. OOP may be utilized in manufacturing system simulation
software, for instance, as well as other design and production applications, and mobile apps.
The structure of an object-oriented programmer lends itself well to team programming, where
tasks are delegated to individuals. Code reuse, scalability, and efficiency are three further gains
from OOP.
Object-oriented programming (OOP) begins with an activity known as data modelling, in which
the objects the programmer wishes to manage are gathered together and their relationships are
established.
Objects may be anything from actual items like humans with identifying information like names
and addresses to discrete software components like widgets. (www.techtarget.com, 2023)
Class:This is the object's blueprint, detailing its core functionality in the form of fields, attributes,
and methods. Members refer to these properties and methods, and they may be accessed in
accordance with the access modifiers specified at member declaration.
Object: The process of declaring and instantiating an object by invoking its class's constructor is
known as "instance instantiation." The state of an object will store information that the class's
attributes may access.
Inheritance: Here we are, at the end of the third phase. Inspection, cleaning, transformation, and
visualisation will be applied to the data in order to extract useful information from it by eliminating
irrelevant details and replacing them with more relevant ones.
Polymorphism: The term "polymorphism" refers to the ability to carry out a single activity in many
distinct ways. Both method overloading and method overriding allow for Polymorphism in Java.
Polymorphism at compile time is also known as method overloading, whereas polymorphism at
runtime is known as method overriding.
Encapsulation: Encapsulation is the process of putting many pieces of code into one, unified
module, or Class, as is done in Java. Java's classes make it easy to implement the encapsulation
technique used in object-oriented programming. To be encapsulated, a Java object or Java Bean
must have members that are only accessible via the class's getters and setters (private access
modifier).
Abstraction: The practice of concealing the implementation of functionality by exposing just the
necessary interfaces or access ways to execute the implementation class methods is known as
object-oriented feature abstraction. Java's Interface and Abstract Class constructs allow for this
level of abstraction. (Pedamkar, 2023)
Encapsulation allows you to hide the internal details of a class from the outside world. In the
library catalog system, this means that sensitive or critical data, such as book availability or user
information, can be hidden from direct access and manipulation. For example, you can make
certain attributes of the Book or User classes private, ensuring that only specific methods within
the class can modify them.
By providing well-defined public interfaces (i.e., methods) and making data private,
encapsulation enables controlled access to the class's properties. This allows you to enforce access
policies and validation checks. For example, you can restrict the modification of a book's
availability status to specific methods and prevent unauthorized changes.
Encapsulation allows for changes to the internal implementation of a class without affecting the
code that uses the class. This is crucial for maintaining and evolving a library catalog system over
time. If the internal structure of the Book class changes, client code that uses the class should
remain unaffected as long as the public interface remains consistent.
3.7.4 Code Organization
Encapsulation encourages well-structured and organized code. Classes are self-contained units
with their own attributes and methods, making the code easier to understand, manage, and
maintain. This separation of concerns also promotes code reusability.
Data Protection: Encapsulation shields the internal data of a class from unauthorized access. This
prevents accidental data corruption and enforces access control.
Modularity: It promotes modularity and helps in breaking down complex systems into manageable
and independent units (classes). Each class focuses on its own set of data and functionality.
Code Flexibility: Encapsulation allows you to modify the internal implementation of a class
without affecting other parts of the code that rely on it. This enhances code flexibility and
maintenance.
Error Handling
Implement robust error handling and exceptions to provide meaningful error messages and prevent
the system from crashing in case of unexpected issues.
Optimize Encapsulation
Review your classes and methods to ensure that data encapsulation is applied consistently. Make
sure that class attributes are private and accessed through getters and setters.
Interactive User Interface
Implement a user-friendly text-based menu system that guides users through different operations,
validates inputs, and provides clear feedback.
3.9 Imperative Abstract knowledge sorts of area unit the premise for object orientation
The concept of "Abstract Data Types" (ADTs) is fundamental to object-oriented programming.
Abstract Data Types refer to a high-level description of data and the operations that can be
performed on that data, without specifying the details of how the data is represented or how the
operations are implemented. These abstract data types are the basis for creating objects in object-
oriented programming.
In object-oriented programming, objects are instances of classes, and classes define the blueprint
for creating objects. These classes encapsulate both data (attributes or properties) and behaviors
(methods or functions). The key idea here is that the data is encapsulated within the class, and
access to the data is controlled through the class's methods. This encapsulation is a form of
abstraction because it hides the internal details of how data is stored and manipulated.
By using abstract data types and encapsulation, object-oriented programming promotes the idea of
treating objects as black boxes. Users of objects (other parts of the program) don't need to know
how the object is implemented; they only need to know what operations are available and how to
use them. This concept of data hiding and exposing a controlled interface for interacting with
objects leads to modularity, reusability, and easier maintenance of code.
In summary, abstract data types and encapsulation are indeed the basis for object orientation. They
enable the creation of objects with well-defined interfaces and hide the internal complexity,
promoting the core principles of object-oriented programming: encapsulation, inheritance, and
polymorphism. These principles are central to designing software systems that are organized,
extensible, and easier to understand and maintain.
3.10 Demonstrate how the implementation of an ADT/algorithm solves a well-defined
problem.
The Bus Reservation System described can indeed be implemented using various Abstract Data
Types (ADTs) and algorithms, as outlined. Here's a summary with the pronouns removed:
- ADT: Algorithm
- Problem: Finding available buses between two points.
- Solution: Implement an algorithm that iterates through the list of buses and checks if the
starting and ending points match the user's input.
- ADT: Iteration
- Problem: Displaying confirmed reservations.
- Solution: Use iteration to go through the list of confirmed reservations and display each
reservation along with relevant customer and bus information.
Implementing these ADTs and algorithms efficiently manages bus reservations, enhances the user
experience, and simplifies the management of bus reservations for both customers and bus
operators.
Graphs are a fundamental and versatile data structure, integral to a wide range of applications
across various domains. In computer science, graphs are employed to model complex
relationships, networks, and structures. (geeksforgeeks, 2023)
Weighted Graph
In unweighted graphs, there are no values associated with the edges; edges are considered to
have uniform weight.
These graphs are simpler to work with for certain algorithms like breadth-first search, which
don't consider edge weights.
Undirected Graph
The relationships between objects in an undirected graph are symmetric, like mutual friendships
on a social network.
These graphs are useful for modeling relationships where interactions are reciprocal.
Figure 84 Undirected Graph
Directed graphs (digraphs) have objects connected by directed edges, which go from one node to
another.
The relationships in directed graphs are asymmetric, like one-way streets in a city.
Digraphs are suitable for modeling processes or flows where direction matters, such as computer
networks or dependency management.
Figure 85 Directed Graph (Digraph)
Shortest route algorithms, by design, often use a graph, G, as input. There are nodes (called
vertices) and connections between them (called edges) in this network. A graph is said to be
weighted if and only if its edges carry weights. The graph is said to be undirected if and only if its
edges do not have a direction. The graph may even have cycles at times. These nuances are what
make certain algorithms more effective than others for a given kind of graph.
Figure 86 The same graph as above, but directed
Even shortest route algorithms come in a variety of flavours. Find the shortest route from A to B,
or from A to every other point in the graph, depending on the situation.
The use of shortest route algorithms is widespread. As was mentioned before, shortest route
algorithms are used by applications such as Google Maps and Apple Maps. Additionally, studies
involving road networks, operations, and logistics benefit greatly from them. Most computer
networks, including the Internet, rely heavily on shortest route algorithms.
A shortest path method is at the heart of every route selection tool you may utilise. For example,
Google Maps allows you to enter a beginning and a finish location and returns the optimal route.
(brilliant, 2023)
4.1 Dijkstra’s Algorithm
When compared to other algorithms, Dijkstra's Algorithm stands out owing to its ability to locate
the shortest route from a given node to all other nodes in the same graph data structure. This implies
that, assuming the network doesn't change, the method seeks for the shortest route to every possible
node, rather than merely the shortest path from the beginning node to a specified node.
The algorithm continues to iterate until all possible nodes have been visited. This means that,
barring any changes to the graph data structure, Dijkstra's method only has to be performed once
and the results stored for future use.
To get the most up-to-date shortest pathways for your data structure after a graph update, you'll
need to repeat the graph.
For example, in our routing scenario, if we know that some roads are heavily congested, blocked,
undergoing works, etc., but still want to get from point A to point B as quickly as possible, we can
use Dijkstra's algorithm to find the shortest path while avoiding any edges with larger weights.
The Bellman-Ford algorithm seeks the shortest route from a given node to every other node in the
network, much like Dijkstra's method. Bellman-Ford may be slower than the former, but its
adaptability more than makes up for its sluggishness. While Dijkstra's method cannot handle
graphs with negative edge weights, Bellman-Ford can.
Note that there is no shortest or cheapest route in the graph if the edges add to a negative number,
as in the case of a negative cycle. Since the algorithm dies at the end of a negative cycle, it cannot
identify the optimal path. The presence of negative cycles may be reported by Bellman- Ford.
Johnson's approach has a runtime that scales with the number of edges, hence it performs best on
sparse networks. Therefore, the fewer edges there are, the quicker a route may be generated.
In contrast to previous shortest route algorithms, this one uses input from two additional methods.
It starts by eliminating negative cycles and edges using Bellman-Ford's cycle detection algorithm.
Then, using this modified graph, it applies Dijkstra's algorithm to find the shortest routes in the
given graph. (myrouteonline, 2023)
4.3. Choosing the shortest path formula for the state of affairs
In the context of the bus reservation system scenario, a First-Come-First Serve (FCFS) strategy is
a simple approach used to manage the waiting queue of customers who have requested a new seat
when no seats are available on a bus. FCFS follows the principle that the customer who makes a
seat request first is the one who will be allocated a seat first when it becomes available.
Customer Requests a New Seat: When a customer, who couldn't reserve a seat due to
unavailability, requests a new seat, their request is added to the end of the waiting queue. The
system notes the customer's request time.
When a previously reserved seat is canceled by a customer, it becomes available for allocation.
FCFS Allocation
The system checks the waiting queue and identifies the customer who made the earliest seat
request. This customer is then allocated the newly available seat. The system updates the
reservation status for this customer to "confirmed."
Notification
The customer who receives the seat is immediately notified through a message, informing them
of the successful allocation.
Remaining Customers
Any customers who requested seats after the customer who just received a seat will remain in the
queue. They will be considered in the same FCFS order when additional seats become available.
Figure 87 First-Come-First Serve (FCFS)
2. Dijkstra's Algorithm
Dijkstra's calculation may be a broadly utilized chart look calculation outlined to discover the
most limited way between hubs in a weighted graph. It's particularly useful after you got to
discover the foremost effective course between areas in a transportation framework like a
transport reservation framework
Dijkstra's calculation can be utilized to discover the most brief and most efficient bus routes
between diverse cities or areas inside the transportation arrange. Within the setting of the
transport reservation framework, it can offer assistance clients discover the most excellent course
based on components like separate, travel time, or fetched.
The transport reservation framework can speak to the transportation arrange as a weighted chart.
In this chart, cities or areas are hubs, and the edges between them speak to transport courses. The
weight of each edge can mean diverse components, such as travel remove or time, or indeed the
passage.
User-Friendly Directing
By executing Dijkstra's calculation, the transport reservation framework can give clients with a
client- neighborly interface for selecting their flight and entry areas. The calculation at that point
calculates the most limited course considering the selected criteria and gives clients with
important data.
Real-Time Overhauls
Dijkstra's calculation can be adjusted to handle real-time overhauls, such as activity conditions
or street closures. This guarantees that clients get the foremost precise and up-to-date course
data.
Dijkstra's calculation can be coordinates with other highlights of the framework, such as situate
accessibility and reservation. Once clients select a course, the framework can check situate
accessibility on the buses along that course and permit them to form reservations.
In some cases, the bus reservation system might need to account for factors that could add extra
time or distance to a route, such as traffic delays or detours. These factors could be represented as
negative weights in the graph.
If the system needs to optimize routes by considering both positive and negative weights (e.g.,
minimizing travel time while accounting for potential delays), Bellman-Ford can be used. It can
find the path that minimizes the overall cost, even when negative weights are involved.
Bellman-Ford can also detect negative weight cycles, which might indicate scenarios where no
matter how you route a bus, it will never reach its destination within a reasonable time. Detecting
such cycles can be important for route planning and resource allocation.
Once the optimized route is found, passengers can make reservations based on their preferences,
whether they prioritize speed or cost-effectiveness.
In summary, Bellman-Ford can be useful in scenarios where routes may involve negative weights
or where detecting negative weight cycles is important. It provides a more versatile approach to
route optimization and resource allocation within the bus reservation system.
Figure 89 Bellman-Ford
Initialization: We'll start by initializing data structures to keep track of the shortest distances from
City A to other cities. We'll also maintain a set of unvisited cities. Initially, all distances to
unvisited cities are set to infinity, except City A, which is set to 0. The unvisited set includes all
cities.
Let's revisit our example graph and use a table to illustrate Dijkstra's algorithm for finding the
shortest route from City A to all other cities:
Figure 90 map location
A 0 Yes
B ∞ No
C ∞ No
D ∞ No
E ∞ No
F ∞ No
Iteration 1
Visit City B: We find that the distance from City A to City B (5) is less than the current known
distance (infinity). So, we update the distance from City A to City B to 5.
Visit City D: Similarly, we find that the distance from City A to City D (2) is less than the current
known distance (0). We update the distance from City A to City D to 2. We also mark City D as
visited.
A 0 Yes
B 5 Yes
C ∞ No
D 2 Yes
E ∞ No
F ∞ No
Table 15 The distance from City A to City B is 5. We update the table
Figure 91 The distance from City A to City B is 5.
A 0 Yes
B 5 Yes
C ∞ No
D 2 Yes
E ∞ No
F ∞ No
Table 16 Shortest Distance from A
Iteration 2
Visit City C: The distance from City A to City C (5 + 3 = 8) is shorter than the current known
distance (infinity). the distance from City A to City C to 8.
Visit City E: The distance from City A to City E (2 + 2 = 4) is shorter than the current known
distance (infinity). the distance from City A to City E to 4.
Now explore the next unvisited city with the shortest tentative distance, which is City D
A 0 Yes
B 5 Yes
C 8 Yes
D 2 Yes
E 6 Yes
F 9 Yes
Table 17 Shortest Distance from A
Figure 92 Iteration 2
Iteration 3
Visit City F: The distance from City A to City F (8 + 1 = 9) is shorter than the current known
distance (infinity). We update the distance from City A to City F to 9.
A explore the remaining unvisited city, which is City C. There are no updates in this step
because we've already found the shortest distances.
Figure 93 Iteration3
Iteration 4
The shortest route from City A to City D is 2, and the shortest route from City A to City F is 9.
Therefore, if a user in the bus reservation system wants to travel from City A to City D, the
algorithm has determined that the shortest route is via City D, with a total distance of 2.
Figure 94 java code
4.3.2. Illustration the operation for First-Come-First-Serve
Algorithm
let's walk through how the First-Come-First-Serve (FCFS) scheduling algorithm works in the
context of the bus reservation system. In this detailed example, we'll illustrate FCFS for a specific
route from City A to City F with limited seats.
4.5 Initialization
The reservation order is determined by the time of the reservation request. C1, C2, and C3 made
their reservations sequentially.
Allocation
- C1: Seat 1
- C2: Seat 2
- C3: Seat 3
4.9 Notification
Suppose more customers request reservations after all seats are booked:
- As all seats are booked, C4 and C5 are placed in the waiting list queue in the order they
requested reservations.
4.12 Cancellation
- The FCFS algorithm now allocates the available seat (Seat 2) to the first customer in the
waiting list queue, which is C4.
- C4: Seat 2
Final Notification
A sorting algorithm is a sequence of instructions that takes an array (also known as a list) as input,
sorts the array according to predetermined criteria, and returns the original array in sorted order.
Data structures like binary trees and heaps, as well as concepts like Big-O notation and divide-
and-conquer strategies, are commonly introduced alongside sorting algorithms at the start of a
computer science course. Choosing a sorting algorithm requires careful consideration of a variety
of criteria. (Karleigh Moore, 2023)
In order to sort data quickly, a rapid sort algorithm employs a technique that segments a big array
into smaller arrays. The provided array is divided into subarrays, with one member chosen as the
pivot. A pivot value is used to split a huge array into two arrays, one of which will include values
less than the pivot value and the other array will contain values more than the pivot value.
Quicksort uses a pivot to divide an array into two halves, which are then sorted recursively.
Bubble Sort
When it comes to sorting algorithms, this one is the bare minimum. In this procedure, the intended
order (i.e., ascending or descending) is disrupted by comparing and exchanging nearby items.
To put it another way, if you're using bubble sort to place things in ascending order, it'll check the
first two items in the array to see whether they're comparable. The algorithm will swap the two
elements and continue when the second element is less than the first.
Figure 101 Bubble Sort
Merge sort
Both merge sort and rapid sort are based on the divide-and-conquer algorithm. The merge sort
algorithm is a common and effective data sorting technique. This function takes the whole list and
divides it in half, calls itself twice, and then merges the sorted results. We need to define the
merge() method so that the data may be combined.
Sublists are split in half repeatedly until no further divisions can be made. We sort the newly
formed two-element lists as we merge the single-item lists into them. A pair of sorted items is
paired with a list of sorted items of the same size, and so on.
Figure 102 Merge sort
Insertion Sort
The Insertion Sort is a straightforward technique for sorting data that functions similarly to sorting
a deck of cards by hand. We start with the assumption that the deck is sorted and choose a card
that is not in order. Unsorted cards bigger than the first are moved to the right; those lower in value
are moved to the left. All cards that haven't been assigned a position are removed in the same
manner.
Selection Sort
As an in-place comparison-based algorithm, Selection Sort splits the list in half, with the sorted
half on the left and the unsorted half on the right. The smallest item in the unsorted array is moved
to the front of the sorted array, and the item on the left is moved to the back. During this procedure,
the rightmost member of the unsorted array is shifted to the right by one position.
here is the textual representation of the QuickSort algorithm for sorting bus reservations by bus
ID without pronouns
1. The algorithm selects a "pivot" element. In this case, it can be the last reservation (Bus ID
103, Customer D).
2. It partitions the list into two sublists. All elements with a bus ID less than 103 go to the
left sublist, and all elements with a bus ID greater than 103 go to the right sublist.
3. The algorithm is then applied recursively to the left and right sublists.
4. After all recursive calls are complete, the reservations are sorted by bus ID.
After applying the QuickSort algorithm, the sorted reservations would appear as follows:
This represents the sorted bus reservations in ascending order of bus ID.
here's a Java code illustration of sorting bus reservations by bus ID using the bubble sort
algorithm with pronouns removed
Figure 104 Use QuickSort for bus reservations
Figure 105 Use QuickSort for bus reservations
This Java code illustrates sorting bus reservations by bus ID using the bubble sort algorithm. The
Reservation class represents individual reservations with bus ID and customer name attributes.
The BusReservationSystem class allows adding reservations, sorting them by bus ID, and
displaying the sorted reservations. The final result displays the sorted reservations by bus ID.
Merge Sort is a popular and efficient sorting algorithm that operates using a divide-and-conquer
strategy. In the context of the bus reservation system scenario, Merge Sort can be used to sort
reservations based on Bus IDs.
Divide
- The unsorted list of reservations is divided into two halves. The algorithm finds the
middle point of the list to create two sublists.
Conquer
- Each sublist is recursively sorted using the same Merge Sort algorithm. This process
continues until we have divided the sublists into smaller, sorted sublists. The base case of
the recursion is when a sublist has only one element, as a single element is considered
sorted.
Merge
- The sorted sublists are merged to produce a new sorted list. This merging step involves
comparing elements from both sublists and adding them to the new sorted list in ascending
order of Bus IDs. The merging continues until all elements from both sublists are included
in the final sorted list.
Repeat
- The Divide-Conquer-Merge process is repeated for each level of recursion until the entire
list is sorted.
- Once all the elements are merged, the result is a sorted list of reservations based on Bus
IDs.
2. there are many sorting algorithms available, and the choice of which one to use depends
on factors like the size of the dataset, data distribution, and performance requirements.
Here's an example of sorting bus reservations based on Bus ID using the Merge Sort
algorithm in Java:
Figure 106 Merge Sort algorithm for bus reservations
References
Aggarwal, A., & Gupta, P. (2012). Data Structures and Algorithms in Java. Pearson Education
India.
Aho, A. V., Hopcroft, J. E., & Ullman, J. D. (2003). The Design and Analysis of Computer
Algorithms. Addison-Wesley.
Baase, S. (2008). Computer Algorithms: Introduction to Design and Analysis. Pearson Prentice
Hall.
Baeza-Yates, R., & Ribeiro-Neto, B. (2011). Modern Information Retrieval: The Concepts and
Technology behind Search. Addison-Wesley.
Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2009). Introduction to Algorithms (3rd
ed.). The MIT Press.
Drozdek, A. (2012). Data Structures and Algorithms in C++ (4th ed.). Cengage Learning.
Ford, W., & Topp, D. (2012). Java Programming: From Problem Analysis to Program Design
(6th ed.). Cengage Learning.
Gaddis, T. (2012). Starting Out with Java: From Control Structures through Objects. Pearson
Higher Education.
Goodrich, M. T., & Tamassia, R. (2014). Data Structures and Algorithms in Java (6th ed.). Wiley.
Horowitz, E., & Sahni, S. (2008). Fundamentals of Computer Algorithms. Galgotia Publications.
Knuth, D. E. (1973). The Art of Computer Programming, Volume 1: Fundamental Algorithms (3rd
ed.). Addison-Wesley.
Lafore, R. (2002). Data Structures and Algorithms in Java (2nd ed.). Sams Publishing.
Levitin, A. (2007). Introduction to the Design & Analysis of Algorithms. Pearson Education.
Li, T., & Hsu, S. H. (2010). Data Structures and Algorithm Analysis in Java. Pearson Prentice
Hall.
Robson, M., & Perrott, G. (2004). Advanced Java Programming. Cengage Learning.
Silva, J. A., & Oliveira, F. (2007). Java Algorithms: A Guide to Efficiency. Prentice Hall.
Spence, R., & Deitel, H. (2007). Java: How to Program (8th ed.). Prentice Hall.