Determine the operations of a memory stack and how it is used to implement function calls in a computer ...141.. Using an imperative definition, specify the abstract data type for a soft
Stack
Stack is a linear data structure which follows a particular order in which the operations are performed The order may be LIFO (Last in First Out) or FILO (First in Last Out)
Mainly the following three basic operations are performed in the stack:
Adds an item in the stack If the stack is full, then it is said to be an Overflow condition Pop:
Removes an item from the stack The items are popped in the reversed order in which they are pushed If the stack is empty, then it is said to be an Underflow condition Peek or Top:
Return top element of stack
Returns true if stack is empty, else false
Example code of stack When you input a number, for example input = 6: return 77; multiply(Integer 11 * 7 = 77) – minus(Integer - 26 – 15 = 11) plus(Integer - 6 + 20 = 26) Input(Integer - 6) result(Integer - multiply) data(Integer - 6)Scan(Scanner - System.in)
Queue
Queue is also an abstract data type or a linear data structure, just like stack data structure, in which the first element is inserted from one end called the REAR (also called tail), and the removal of existing element takes place from the other end called as FRONT (also called head) This makes queue as FIFO (First in First Out) data structure, which means that element inserted
Which is exactly how queue system works in real world If we go to a ticket counter to buy movie tickets, and are first in the queue, then we will be the first one to get the tickets Right? Same is the case with Queue data structure Data inserted first, will leave the queue first
The process to add an element into queue is called Enqueue and the process of removal of an element from queue is called Dequeue
Link list
It is a data structure that contains a finite sequence of n data element Linked list is the second most-used data structure after array
Linked list can be visualized as a chain of nodes, where every node point to the next node
Fig: representation of the link list
Following are the various types of the link list:
Simple Linked List − Item navigation is forward only
Doubly Linked List − Items can be navigated forward and backward
Circular Linked List − Last item contains link of the first element as next and the first element has a link to the last element as previous
Following are the basic operation supported by the link list:
Insertion − Adds an element at the beginning of the list
Deletion − Deletes an element at the beginning of the list
Display − Displays the complete list
Search − Searches an element using the given key
Delete − Deletes an element using the given key.
How stack help to store the required data?
Basically, stack is used to store the data and it has small size so, that the large amount of data cannot be store in the stack After inserting the data then only the storing of the data could be done For the insertion of the data I am using the link list data structure and in order to store the data I am using the stack data structure
What is a Binary Search Tree?
Binary Search Tree (BST) is a basic data structure in which each node has at most two children, referred to as left and right children, and the top node in the tree is called root It also fulfills the binary search requirement, stating that the key in each node must be greater than or equal to any key stored in the left sub-tree, and less than or equal to any key stored in the correct sub-tree Binary search tree enables fast search, addition and removal of items They keep their keys in order, so that other searches and operations can apply the principle of Binary Search: when looking for a key in a tree (or where to insert a new key), they cross a tree from root to leaf, comparing it to the key stored in it nodes and decide, by comparison, to continue searching in the left or right subtree On average, this means that each comparison allows operations to jump to about half of the tree, so that each search, insertion or deletion takes time relative to the logarithm of the number of items stored in the tree This is much better than the linear time required to find an item with the key in the array (unsorted), but slower than the same operation on the hash table
Tree data structures are notable for their unique storage mechanism Each node in the tree holds a specific value, ensuring that no empty nodes exist If a node lacks a value, it is considered non-existent This fundamental property underlies the structure and organization of data within trees.
How to find values in BST, as the name might suggest, a common use case for a binary search tree is to find if there are values Let's look at an example:
How to insert a value into BST, it is also useful if you can add something to the tree Doing so is actually quite easy, and looks like a quest You start at the root If the value you want to enter is missing, go left If it's more, go right One caveat is that you cannot enter an existing value BTS cannot have duplicate values, because the value is not greater or less than itself!
To avoid this, at every step along the way, just make sure that the value you are trying to enter does not match the node you are currently viewing If that happens, just blame it or do something
Demonstration of the insertion operation
In the binary search tree, the insertion operation is performed with time complexity O (log n) In the binary search tree, new nodes are always included as leaf nodes The insertion operation is performed as follows:
Step 1 - Create a newNode with the given value and set its left and right to NULL Step 2 - Check whether the tree is empty
Step 3 - If the tree is Empty, then set the root to newNode
Step 4 - If the tree is Not Empty, then check whether the newNode value is smaller or larger than the node (here is the root node)
Step 5 - If the newNode is smaller than or equal to the node then switch to its left If the newNode is larger than the node then move to the correct child
Step 6- Repeat the steps above until we get to the leaf node (that is, to NULL)
Step 7 - After reaching the leaf node, enter newNode as the remaining child if the newNode is smaller or equal to the leaf node or enter it as the correct child
Construct a Binary Search Trees by entering the following sequence of numbers 65, 10, 40, 5,
82, 75 and 90 The element is included in the Binary Search Tree as follows:
Determine the operations of a memory stack and how it is used to implement function
The operations of a memory stack
Stack memory, a temporary data storage mechanism, functions as a first-in, last-out buffer, resembling a stack data structure This memory usage mechanism utilizes the system memory to store data, ensuring that the most recently added item is accessed first, while older items remain in the stack until they are retrieved.
Figure 1 Example of stacks / queues
Items in a stack are inserted or removed in a linear order and not in any random sequence As in any queue or collection that is assembled, the data items in a stack are stored and accessed in a specific way In this case, a technique called LIFO (Last In First Out) is used This involves a series of insertion and removal operations which we will discuss in the following section.
LIFO (Last In First Out)
When a stack is accessed (there are inserted or deleted items), it is done in an orderly manner by LIFO LIFO stands for Last In First Out Computers use this method to request service data that the computer's memory receives LIFO dictates that data is last inserted or stored in any particular stack, must be the first data to be deleted If that applies to our queue for movies in Figure 1 above, there will be chaos! The operations on the stack are discussed in the following sections with image on the below:
Figure 2 : Last in First out
Stack Operations
Push operation involves inserting data items into a stack Let us check our restaurant plate dispenser in Figure 9 Operation pushes additional plates (data items) into the plate dispenser (stack) The first plate is pushed down to the bottom of the stack with all subsequent plates in the following order after it The first inserted data item is the most inaccessible and is located at the bottom of the stack
Pop operation removes data items from the stack, with the last added item being the first to be deleted This process operates in a LIFO (Last-In, First-Out) manner, akin to a spring loading system that pushes the stack upward with each deletion In memory, items continue to be accessed sequentially, with the last added item being the first to be accessed and removed.
In this operation, no data items are added or deleted from the stack The snapshot operation only requires the address location of the data item at the top of the stack (the last item is pushed)
In this operation, it does not have any data items are added or deleted from the stack The search operation requires that geographical local of any data items in the stack It located the item at the top of the stack.
How it is used to implement function calls in a computer stack memory in computers
The first stack deployment is based on the use of registers, in which data is moved in a parallel manner during Push and Pop operations Modern stack deployment is based on the main memory usage supported by special registers that make it easy to access and manage the stack
A stack is reserved by the operating system, sequences of consecutive memory locations The boundary of the stack is determined by two special registers - the stack base register and the stack limit register hold the address of the stack top and lower boundary positions The address space between these addresses is excluded from other uses than the stack implementation The top of the stack is determined by keeping the address in the third register called the stack pointer register Before the computer starts executing the program, the top of the stack register is set to the contents of the stack base register After each Push operation, the contents of the stack pointer register are changed according to the number of bytes corresponding to the stack in the stack limit direction After each Pop operation, the content of the stack pointer is changed in the direction of the stack base
Figure 4 Stack implementation the computer- the top of the stack in the memory
The figure above shows the organization of the stack in the main memory, in which the top of the stack is accessed only in memory Another solution, shown in the figure below, assumes that the top of the stack and the position just below the top, is stored in special processor registers: the top of the stack register and the top register -first.
Stack memory implements function call in computer
Among the instructions that control computers, we can find subroutine call instructions with the acronym "Call" and instructions for returning subroutines with the acronym "Ret" A subroutine is a series of instructions that end with the "Ret" return command In the subroutine the subroutine always has the address of the first instruction in a subprogram called the subroutine address Mechanism of subroutine calls and the execution of the "Call" i "Ret" commands based on the use of the stack Execute the "Call" subroutine command including:
1 stored in the stack of the program counter's current content (ie, the return address executes the next instruction after the call) with the "Push" operation,
2 write to the program that accesses the embedded address in the "Call" guide,
3 take the next tutorial according to the new content of the program counter
The address written to the stack will be used by the "Ret" return command to automatically return from the subroutine to the next command
1 The return execution from the "Ret" subcommand includes:
2 Read from the top of the stack of the return address (to successfully instruct the "call" command),
3 write this address to the program counter,
4 perform the "Pop" operation on the stack,
5 Fetch a new guide according to the new content of the program counter
The address written to the stack in a subroutine call is sometimes called a trace and the subroutine call is called a hop with a trace Often use nested subroutine calls, in which during subroutine execution, new subroutine is called from its body The mechanism of returning from trace subroutines stored in the stack allows to automatically return the next program call context with the correct return order preserved The figure below shows actions related to nested subroutine calls from a top program thread In the subroutine call 1 (Call 500 is stored at address 100), the return address 101 is stored in the stack In the call of subprogram 2 (Call 900 is written at address 600), the return address 601 is saved in the stack When returning from sub-program 2, address 601 is taken from the stack When returning from subroutine 1, address 101 is taken from the stack
Figure 6 The use of stack in subroutine calls
Illustrate, with an example, a concrete data structure for a First In First out (FIFO) queue
First in First out (FIFO) Queue
A Queue is a linear structure which follows a particular order in which the operations are performed The order is First In First Out (FIFO) A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first The difference between stacks and queues is in removing In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.
Linear operations may involve starting or defining a queue, using it, and then deleting it completely from memory Here we will try to understand the basic operations of a line - enqueue () - add (save) items to a queue dequeue () - removes (access) items from the queue
Enqueue Operation o Queue maintains two data pointers, font and rear o The following steps should be taken to enqueue (insert) data into queue:
Step 1: Check if queue is full
Step 2: if queue is full
Produce overflow error and exit
Increment rear pointer to point next empty space and add data element to The queue location, where rear is pointing
Dequeue Operation
Accessing data from queue is a process of two steps
Access the data from where font is pointing
And remove the data after access
The following steps are taken to perform dequeue operation
Step 1: Check is queue is empty
Step 2: if queue is empty
Produce underflow error and exit
Access data where font is pointing, increment font pointer to point next available data element
Some more functions are needed to make the above-mentioned queue operations effective This is: peek - Gets the element in front of the queue without removing it () isfull () - Check for full rotation isempty () - Check if the line is empty
FIFO is an abbreviation for first in, first out It is a method for handling data structures where the first element is processed first and the newest element is processed last
In this example, following things are to be considered:
There is a ticket counter where people come, take tickets and go
People enter a line (queue) to get to the Ticket Counter in an organized manner The person to enter the queue first, will get the ticket first and leave the queue The person entering the queue next will get the ticket after the person in front of him
In this way, the person entering the queue last will the tickets last
Therefore, the First person to enter the queue gets the ticket first and the Last person to enter the queue gets the ticket last.
Compare the performance of two sorting algorithms
Bubble Sort
Bubble Sort is a basic calculation used to manage or arrange a lot of n elements in an array with n quantities of elements Sort Bubble to analyze all the elements individually and compose them by their qualities In the event that the given array should be organized in ascending order, at that point the bubble type will begin by contrasting the main component of the array with the subsequent component, if the primary component is bigger than the subsequent component, it will change the two elements, and afterward proceed onward to think about the second and third elements, and so on In the event that we have a sum of n elements, at that point we have to rehash this procedure for n-multiple times This is known as a bubble type, on the grounds that with each total emphasis of the biggest component in a given array, it bubbles towards the last spot or most noteworthy index
The bubble sort algorithm is performed using the following steps:
Step 1: Starting with the first element (index = 0), compare the current element with the next element in the array
Step 2: If the current element is larger than the next element in the array, swap it
Step 3: If the current element is less than the next element, move to the next element Repeat Step 1
Consider an array with values:
As you can see the number on the above the number are not sorted So we are going to sort it from ascending to descending
We can starts with first two element 6 > 2, 2 is small, so swap the value
7 > 3, 3 is small, so swap the value
After we swap 7 with 3, now we can see that we can still swap the 7 7 > 5, 5 is small so we can swap the value
Next, 7 > 4, 4 is small so we can swap the value
So, this is the results of 1 st iteration which is 2, 6, 3, 5, 4 and 7 We can see the number still not sorted in ascending order so we have to do the 2 iteration nd
Now we can start from the second two element which is number 6 6 > 3, 3 is small so we have to swap the value
Next, 6 > 5, 5 is small so we will swap the value
6 > 4, 4 is small so we have to swap the value
Now, after the 2 iteration we almost reach it, we can see the number almost in order except nd for number 4 So to make sure have the perfect order, we will continue by 3 iteration rd
5 > 4, 4 is small so we will swap the value
Now, the number in every element is in the correct place So once we get the perfect ascending order we will stop now So, the 3 iteration the ascending order is 2, 3, 4, 5, 6 and 7 But keep rd in mind you still did not sorted the number you have to continue by 4 iteration th
Selection Sort
Selection sort is the simplest conceptual sorting algorithm This algorithm will begin to find the smallest element in the array and replace it with the element in the first position, then it will find the second smallest element and swap it with the element in the second position, and it will continue to do this until the entire array is sorted It is called a selection sort because it repeatedly selects the next smallest element and moves it to the right place The Selection Sort Algorithm is used to organize the list of elements in a particular order (Ascending or Descending) The type of selection, the first element in the list is selected and it is compared repeatedly with all the remaining elements in the list If any element is smaller than the selected element (for Ascending order), both are changed so that the first position is filled with the smallest element in the sort order Next, we select the element in the second list and compare it to all the remaining elements in the list If any element is smaller than the selected element, then both are changed This procedure is repeated until the entire list is compiled
The selection sort algorithm is performed using the following steps:
Step 1: Select the first element in the list (that is, Elements in the first position in the list) Step 2: Compare selected elements with all other elements in the list
Step 3: In each comparison, if any element is found to be smaller than the selected element (for Ascending order), then both are changed
Step 4: Repeat the same procedure with the element in the next position in the list until the whole list is sorted
Consider the following unsorted list of elements:
Select the second position element in the list, compare it with all other elements in the list and whenever we found a smaller element than the element at first position then swap those two elements
Select the third position element in the list, compare it with all other elements in the list and whenever we found a smaller element than the element at first position then swap those two elements
Select the fourth position element in the list, compare it with all other elements in the list and whenever we found a smaller element than the element at first position then swap those two elements
Select the fifth position element in the list, compare it with all other elements in the list and whenever we found a smaller element than the element at first position then swap those two elements
Select the sixth position element in the list, compare it with all other elements in the list and whenever we found a smaller element than the element at first position then swap those two elements
Select the seventh position element in the list, compare it with all other elements in the list and whenever we found a smaller element than the element at first position then swap those two elements
Comparison between bubble sort and selection sort:
Adjacent element is compared and swapped
Largest element is selected and swapped with the last element (in case of ascending order)
Time complexity is O(n) Time complexity is O(n ) 2
Inefficient Improved efficiency as compared to bubble sort
It is stable It is not stable
It is slow Fast as compared to bubble sort
In the bubble sort, each element and the adjacent element are compared and swapped as needed On the other hand, the selection sort works by selecting the element and replacing the specific element with the last element The selected element can be the largest or the smallest depending on the order, ascending or descending The complexity of the worst case is the same in both algorithms, namely, O (n ), but the best complexity is different Bubble arrays take 2 n time sequences while selection types use n sequences Bubble sort is a stable algorithm, in 2 contrast, selection sort is unstable The selection algorithm is fast and efficient compared to very slow and inefficient bubble sort The bubble sort algorithm is considered to be the simplest and inefficient algorithm, but the selection sort algorithm is more efficient than the bubble sort Bubble sort also use extra space to store temporary variables and require more swaps.
Examine the advantages of encapsulation and information hiding when using an ADT
Data encapsulation, sometimes referred to as data hiding, is the mechanism whereby the implementation details of a class are kept hidden from the user The user can only perform a restricted set of operations on the hidden members of the class by executing special functions commonly called methods The actions performed by the methods are determined by the designer of the class, who must be careful not to make the methods either overly flexible or too restrictive This idea of hiding the details away from the user and providing a restricted, clearly defined interface is the underlying theme behind the concept of an abstract data type (Craig, 1996)
The advantage of using data encapsulation comes when the implementation of the class changes but the interface remains the same For example, to create a stack class which can contain integers, the designer may choose to implement it with an array, which is hidden from the user of the class The designer then writes the push() and pop() methods which puts integers accessible to the user Should an attempt be made by the user to access the array directly, a compile time error will result Now, should the designer decide to change the stack's implementation to a linked list, the array can simply be replaced with a linked list and the push() and pop() methods rewritten so that they manipulate the linked list instead of the array The code which the user has written to manipulate the stack is still valid because it was not given direct access to the array to begin with (Craig, 1996)
For example, we operate the washing machine through a power button We turn on the power button, the engine starts and when we turn it off, the engine stops We do not know what the mechanisms are That's encapsulation.
Using an imperative definition, specify the abstract data type for a software stack
Specify thfy thfy thfy thfy the e e e e abstrabstrabstrabstrabstraaaaactctctct data tyctdata tydata tydata tydata type for pe for pe for pe for a softpe for a softa softa softa software sware sware sware sware stttttaaaaack ck ck ck ck
A software stack is a set of programs that work together to produce a result, typically an operating system and its applications For example, a smartphone software stack comprises the operating system along with the phone app, Web browser and other basic applications A software stack may also refer to any group of applications that work in sequence toward a common result or any set of utilities or routines that work as a group See stack, application stack and protocol stack In addition, to allow them to work together, the required abstract data types such as Stack (LIFO) and Queue (FIFO)
So, in order to better understand the software stack, we find out about stack operation on Android device For each application running on an Android device, the runtime system will maintain an active Stack When an application is executed, the application's first operation is started to be placed on the stack When a second operation is started, it is placed on the top of the stack and the previous activity is pushed down Operation at the top of the recommended stack is active (or running) When the operation is exited, it is turned off the stack by the running time and the operation is located just below it in the stack to become the current activity Operations at the top of the stack can, for example, just exit because the stack it is responsible for has been completed In addition, the user may have selected the Back on screen button to return to the previous activity, causing the current activity to be disconnected from the stack by the runtime system and therefore destroyed A visual representation of the Android Activity Stack is illustrated in Figure below:
Activities are managed in a stack, with new activities pushed onto the top upon initiation The active activity resides at the top until it is either superseded by a new activity or terminated when the user exits or navigates backward The runtime prioritizes process termination by targeting activities at the stack's bottom if resource constraints arise This stack follows a Last-In-First-Out (LIFO) structure, where the last pushed activity is the first to be removed.
VI Two netwo netwo netwo netwo network work work work work shshshshshortest ortest ortest ortest ortest papapapapattttth algh algh algh algh algorororororithithithithmithmmmmsssss
1 Bellman-ellman-ellman-ellman-Ford Algellman-Ford AlgFord AlgFord AlgorithFord Algorithorithorithorithms ms ms ms ms
Bellman-Ford algorithm solves the problem of single source in the general case, in which edges can have negative weights and oriented graphs If the graph is not guided, it will have to be modified by including two edges in each direction to make it oriented Bellman-Ford has assets that can detect negative weight cycles accessible from the source, which means that no shortest path exists If there is a negative weight cycle, a path can run indefinitely on that cycle, reducing the path cost down Without a negative weight cycle, Bellman-Ford returned the weight of the shortest road along the same road
How the Bellman-Ford Algorithms work?
The Bellman Ford algorithm works by overestimating the length of the path from the starting peak to all other vertices After that, it repeats those estimates by finding new paths shorter than previously overestimated paths Like other dynamic programming problems, the algorithm calculates the shortest path in a bottom-up way First, it calculates the shortest distance that has at most one edge in the path Then it calculates the shortest path with up to 2 edges, etc After the iteration of the external loop, the shortest path with at most i edges is calculated There may be a maximum | V | - 1 edge in any simple path, that's why the outer loop runs | v |
- 1 times The idea is, assuming that there is no negative weight cycle, if we have calculated the shortest paths with most edges i, then repeating on all edges ensures the shortest path to be given the most edges (i + 1) Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex to all other vertices in the given graph Given a graph and a source src peak in the graph, find the shortest path from src to all vertices in the given graph The chart may contain negative weight edges
Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum distance from source is calculated and finalized Initially, this set is empty
Assign a distance value to all vertices in the input graph Initialize all distance values as INFINITE Assign distance value as 0 for the source vertex so that it is picked first While sptSet doesn’t include all vertices
Pick a vertex u which is not there in sptSet and has minimum distance value Include u to sptSet
Update distance value of all adjacent vertices of u To update the distance values, iterate through all adjacent vertices For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v To better understand how it works as well as the algorithm of the Bellman Ford Algorithm, we will provide you with an example Set the source vertex given to 0 Initialize all distances as infinite, except the distance to the source itself The total number of vertices in the graph is 5, so all edges must be processed 4 times
Let all edges be processed in the following order: (B, E), (D, B), (B, D), (A, B), (A, C), (D, C), ( B, C), (E, D) We get distance after all edges are processed for the first time The first row in the original distance The second row shows the distance when the edges (B, E), (D, B), (B, D) and (A, B) are processed The third row displays the distance when (A, C) is processed The fourth row displayed when (D, C), (B, C) and (E, D) are processed
The second iteration ensures that all the shortest paths are at most 2 edges long The algorithm handles all edges 2 more times The distance is minimized after the second iteration, so the third iteration and the fourth time do not update the distance
2 Dijkstrijkstrijkstrijkstrijkstra’s Aa’s Aa’s Aa’s Aa’s Algoritlgoritlgoritlgoritlgorithm hm hm hm hm
Dijkstra's algorithm uses the first width search (not the single-source shortest path algorithm) to solve a single source problem It places a constraint on the graph: it cannot have negative weight edges However, with one limitation, Dijkstra significantly improved the running time of Bellman Dijkstra's algorithm is sometimes also used to solve the shortest path problem of all pairs by simply running it on all internal vertices Again, this requires all edge weights to be positive Dijkstra's algorithm allows you to calculate the shortest path between a node (you choose which button) and every other node in the graph
Djkstra's algorithm works on the basis that all B -> D paths of the shortest path A -> D between vertices A and D are also the shortest path between vertices B and D
Djikstra used this property in the opposite direction, that is, we overestimate the distance of each vertex from the start Then we visit each of its nodes and neighbors to find the shortest path to those neighboring nodes The algorithm uses a greedy approach in the sense that we find the next best solution in the hope that the end result is the best solution for the whole problem For instances, calculate the shortest path between node C and the other nodes in the chart below:
During the execution of the algorithm, we will mark every node with the minimum distance to the C button (our selected node) For node C, this distance is 0 For the rest of the nodes, since we still don't know the minimum distance, it starts with infinity (∞):