DSA
DSA
The study of data structure allows us to understand the organiza on of data and Circular Queue: In Circular Queue, all the nodes are represented as circular. It is similar to the linear Queue except that the last
the management of the data flow in order to increase the efficiency of any process or program. Data Structure is a par cular way element of the queue is connected to the first element. It is also known as Ring Buffer, as all the ends are connected to another
of storing and organizing data in the memory of the computer so that these data can easily be retrieved and efficiently u lized in end. The drawback that occurs in a linear queue is overcome by using the circular queue. If the empty space is available in a
the future when required. The data can be managed in various ways, like the logical or mathema cal model for a specific circular queue, the new element can be added in an empty space by simply incremen ng the value of rear. The main advantage
organiza on of data is known as a data structure. of using the circular queue is be er memory u liza on.
The scope of a par cular data model depends on two factors: 1. First, it must be loaded enough into the structure to reflect the Enqueue: The Enqueue opera on is used to insert the element at the rear end of the queue. It returns void.
definite correla on of the data with a real-world object. 2. Second, the forma on should be so straigh orward that one can Dequeue: It performs the dele on from the front-end of the queue. It also returns the element which has been removed from
adapt to process the data efficiently whenever necessary. the front-end. It returns an integer value. Peek: This is the third opera on that returns the element, which is pointed
Key Features of Data Structures: Robustness: Generally, all computer programmers aim to produce so ware that yields correct by the front pointer in the queue but does not delete it. Queue overflow (isfull): It shows the overflow condi on when the
output for every possible input, along with efficient execu on on all hardware pla orms. This type of robust so ware must queue is completely full. Queue underflow (isempty): It shows the underflow condi on when the Queue is empty, i.e., no
manage both valid and invalid inputs. Adaptability: Building so ware applica ons like Web Browsers, Word Processors, elements are in the Queue.
and Internet Search Engine include huge so ware systems that require correct and efficient working or execu on for many years. Tree: A tree data structure is a hierarchical structure that is used to represent and organize data in a way that is easy to navigate
Moreover, so ware evolves due to emerging technologies or ever-changing market condi ons. Reusability: The features like and search. It is a collec on of nodes that are connected by edges and has a hierarchical rela onship between the nodes. The
Reusability and Adaptability go hand in hand. It is known that the programmer needs many resources to build any so ware, topmost node of the tree is called the root, and the nodes below it are called the child nodes. Each node can have mul ple child
making it a costly enterprise. However, if the so ware is developed in a reusable and adaptable way, then it can be applied in nodes, and these child nodes can also have their own child nodes, forming a recursive structure.
most future applica ons. Thus, by execu ng quality data structures, it is possible to build reusable so ware, which appears to be key points of the Tree data structure.: *A tree data structure is defined as a collec on of objects or en es known as
cost-effec ve and mesaving. Correctness: Data Structures are designed to operate correctly for all kinds of inputs based nodes that are linked together to represent or simulate hierarchy. *A tree data structure is a non-linear data structure because
on the domain of interest. In order words, correctness forms the primary objec ve of Data Structure, which always depends it does not store in a sequen al manner. It is a hierarchical structure as elements in a Tree are arranged in mul ple levels.
upon the problems that the Data Structure is meant to solve. Efficiency: Data Structures also requires to be efficient. It should *In the Tree data structure, the topmost node is known as a root node. *Each node contains some data, and data can be of any
process the data quickly without u lizing many computer resources like memory space. In a real- me state, the efficiency of a type. In the above tree structure, the node contains the name of the employee, so the type of data would be a string.
data structure is a key factor in determining the success and failure of the process. *Each node contains some data and the link or reference of other nodes that can be called children.
Array: Arrays are defined as the collec on of similar types of data items stored at con guous memory loca ons. It is one of the Root: The root node is the topmost node in the tree hierarchy. In other
simplest data structures where each data element can be randomly accessed by using its index number. words, the root node is the one that doesn't have any parent. In the
In C programming, they are the derived data types that can store the primi ve type of data such as int, char, double, float, above structure, node numbered 1 is the root node of the tree. If a node
etc.Proper es of array: *Each element in an array is of the same data type and carries the same size that is 4 bytes. *Elements in is directly linked to some other node, it would be called a parent-child
the array are stored at con guous memory loca ons from which the first element is stored at the smallest memory loca on. rela onship. Child node: If the node is a descendant of any node, then
*Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given the node is known as a child node. Parent: If the node contains
base address and the size of the data element. any sub-node, then that node is said to be the parent of that sub-node.
Linked list: Linked list is a linear data structure that includes a series of connected nodes. Linked list can be defined as the nodes Sibling: The nodes that have the same parent are known as siblings.
that are randomly stored in the memory. A node in the linked list contains two parts, i.e., first is the data part and second is the Leaf Node:- The node of the tree, which doesn't have any child node, is
address part. The last node of the list contains a pointer to the null. A er array, linked list is the second most used data structure. called a leaf node. A leaf node is the bo om-most node of the tree. There
In a linked list, every link contains a connec on to another link. Advantages of Linked Lists over arrays: *Dynamic Array. can be any number of leaf nodes present in a general tree. Leaf nodes can
*Ease of Inser on/Dele on. *Inser on at the beginning is a constant me opera on and takes O(1) me, as compared to also be called external nodes. Internal nodes: A node has atleast one
arrays where inser ng an element at the beginning takes O(n) me,where n is the number of elements in the array. child node known as an internal. Ancestor node:- An ancestor of a node is any predecessor node on a path from the root to
Drawbacks of Linked Lists: *Random access is not allowed. We have to access elements sequen ally star ng from the first that node. The root node doesn't have any ancestors. In the tree shown in the above image, nodes 1, 2, and 5 are the ancestors
node(head node). So we cannot do a binary search with linked lists efficiently with its default implementa on. *Extra memory of node 10. Descendant: The immediate successor of the given node is known as a descendant of a node. In the above
space for a pointer is required with each element of the list. *Not cache-friendly. Since array elements are con guous loca ons, figure, 10 is the descendant of node 5.
there is the locality of reference which is not there in the case of linked lists. *It takes a lot of me in traversing and changing Proper es of Tree data structure: Recursive data structure: The tree is also
the pointers. *Reverse traversing is not possible in singly linked lists. *It will be confusing when we work with pointers. known as a recursive data structure. A tree can be defined as recursively
Types of Linked Lists: Singly-linked list - Singly linked list can be defined as the collec on of an ordered set of elements. A because the dis nguished node in a tree data structure is known as a root
node in the singly linked list consists of two parts: data part and link part. Data part of the node stores actual informa on that is node. The root node of the tree contains a link to all the roots of its subtrees.
to be represented by the node, while the link part of the node stores the address of its immediate successor. Doubly Number of edges: If there are n nodes, then there would n-1 edges. Each
linked list - Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next arrow in the structure represents the link or path. Each node, except the root
node in the sequence. Therefore, in a doubly-linked list, a node consists of three parts: node data, pointer to the next node in node, will have atleast one incoming link known as an edge. There would be
sequence (next pointer), and pointer to the previous node Circular Linked List – In this type of linked list, the last node of the one link for the parent-child rela onship.
linked list contains the link of the first/head node of the linked list in its next pointer Depth of node x: The depth of node x can be defined as the length of the path
Queue: A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle, meaning that the first element added from the root to the node x. One edge contributes one-unit length in the path.
to the queue is the first one to be removed. A queue has two main opera ons: enqueue, which adds an element to the back of So, the depth of node x can also be defined as the number of edges between the root
the queue, and dequeue, which removes the element from the front of the queue. Queue can also be defined as the list or node and the node x. The root node has 0 depth. Height of node x: The height of node x
collec on in which the inser on is done from one end known as the rear end or the tail of the queue, whereas the dele on is can be defined as the longest path from the node x to the leaf node.
done from another end known as the front end or the head of the queue. Applica ons of trees: *Storing naturally hierarchical data: Trees are used to
Applica ons of Queue: *Queues are widely used as wai ng lists for a single shared resource like printer, disk, CPU. *Queues are store the data in the hierarchical structure. For example, the file system. The
used in asynchronous transfer of data (where data is not being transferred at the same rate between two processes) for eg. file system stored on the disc drive, the file and folder are in the form of the naturally hierarchical data and stored in the form of
pipes, file IO, sockets. *Queues are used as buffers in most of the applica ons like MP3 media player, CD player, etc. trees. *Organize data: It is used to organize data for efficient inser on, dele on and searching. For example, a binary tree has a
Queue are used to maintain the play list in media players in order to add and remove the songs from the play-list. logN me for searching an element. *Trie: It is a special kind of tree that is used to store the dic onary. It is a fast and efficient
*Queues are used in opera ng systems for handling interrupts. way for dynamic spell checking. *Heap: It is also a tree data structure implemented using arrays. It is used to implement
Types of Queue: There are two different types of queue that are listed as follows priority queues. *B-Tree and B+Tree: B-Tree and B+Tree are the tree data structures used to implement indexing in databases.
Simple Queue or Linear Queue Circular Queue: In Linear Queue, an inser on takes place from one end while the dele on occurs *Rou ng table: The tree data structure is also used to store the data in rou ng tables in the routers.
from another end. The end at which the inser on takes place is known as the rear end, and the end at which the dele on takes Types of Tree data structure
place is known as front end. It strictly follows the FIFO rule. The major drawback of using a linear Queue is that inser on is done *General tree: The general tree is one of the types of tree data structure. In the general tree, a node can have either 0 or
only from the rear end. If the first three elements are deleted from the Queue, we cannot insert more elements even though the maximum n number of nodes. There is no restric on imposed on the degree of the node (the number of nodes that a node can
space is available in a Linear Queue. In this case, the linear Queue shows the overflow condi on as the rear is poin ng to the last contain). The topmost node in a general tree is known as a root node. The children of the parent node are known as subtrees.
element of the Queue. (edited) *Binary tree: Here, binary name itself suggests two numbers, i.e., 0 and 1. In a binary tree, each node in a tree can have utmost
two child nodes. Here, utmost means whether the node has 0 nodes, 1 node or 2 nodes.
*Binary Search tree: Binary search tree is a non-linear data structure in which one node is connected to n number of nodes. It is means that no element exists in the stack, this state is known as an underflow state. *isEmpty(): It determines whether the
a node-based data structure. A node can be represented in a binary search tree with three fields, i.e., data part, le -child, and stack is empty or not. *isFull(): It determines whether the stack is full or not. *peek(): It returns the element at the given
right-child. A node can be connected to the utmost two child nodes in a binary search tree, so the node contains two pointers posi on. *count(): It returns the total number of elements available in a stack *change(): It changes the element at the given
(le child and right child pointer). Every node in the le subtree must contain a value less than the value of the root node, posi on. *display(): It prints all the elements available in the stack.
and the value of each node in the right subtree must be bigger than the value of the root node. *AVL tree: It is one of the PUSH opera on: The steps involved in the PUSH opera on is given below: *Before inser ng an element in a stack, we check
types of the binary tree, or we can say that it is a variant of the binary search tree. AVL tree sa sfies the property of the binary whether the stack is full. *If we try to insert the element in a stack, and the stack is full, then the overflow condi on occurs.
tree as well as of the binary search tree. It is a self-balancing binary search tree that was invented by Adelson Velsky Lindas. *When we ini alize a stack, we set the value of top as -1 to check that the stack is empty. *When the new element is pushed in
Here, self-balancing means that balancing the heights of le subtree and right subtree. This balancing is measured in terms of a stack, first, the value of the top gets incremented, i.e., top=top+1, and the element will be placed at the new posi on of the
the balancing factor. We can consider a tree as an AVL tree if the tree obeys the binary search tree as well as a top. *The elements will be inserted un l we reach the max size of the stack.
balancing factor. The balancing factor can be defined as the difference between the height of the le subtree and the height of POP opera on: The steps involved in the POP opera on is given below: *Before dele ng the element from the stack, we check
the right subtree. The balancing factor's value must be either 0, -1, or 1; therefore, each node in the AVL tree should have the whether the stack is empty. *If we try to delete the element from the empty stack, then the underflow condi on occurs. *If
value of the balancing factor either as 0, -1, or 1. the stack is not empty, we first access the element which is pointed by the top
Traversal: Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all nodes are connected *Once the pop opera on is performed, the top is decremented by 1, i.e., top=top-1.
via edges (links) we always start from the root (head) node. That is, we cannot randomly access a node in a tree. There are three Sor ng: Sor ng is a process of arranging data in a par cular order, usually in ascending or descending order. Data structures are
ways which we use to traverse a tree −*In-order Traversal *Pre-order Traversal *Post-order Traversal used to store and manage data efficiently. Sor ng is a common opera on performed on data structures to arrange the elements
Preorder traversal: This technique follows the 'root le right' policy. It means in a par cular order. There are many sor ng algorithms available for data structures, and the choice of algorithm depends
that, first root node is visited a er that the le subtree is traversed recursively, on the size of the data, the distribu on of the data, and the desired me complexity.
and finally, right subtree is recursively traversed. As the root node is traversed Bubble sort: Bubble sort works on the repeatedly swapping of adjacent elements un l they are not in the intended order. It is
before (or pre) the le and right subtree, it is called preorder traversal. called bubble sort because the movement of array elements is just like the movement of air bubbles in the water. Bubbles in
So, in a preorder traversal, each node is visited before both of its subtrees. We water rise up to the surface; similarly, the array elements in bubble sort move to the end in each itera on. Although it is simple
start from A, and following in-order traversal, we move to its le subtree B. B to use, it is primarily used as an educa onal tool because the performance of bubble sort is poor in the real world. It is not
is also traversed in-order. The process goes on un l all the nodes are visited. suitable for large data sets. The average and worst-case complexity of Bubble sort is O(n2), where n is a number of items.
The output of inorder traversal of this tree will be − D → B → E → A → F → C Bubble short is majorly used where -*complexity does not ma er *simple and shortcode is preferred
→G The applica ons of preorder traversal include - Algorithm: 1. Start with an array of unsorted numbers 2. Define a func on called “bubbleSort” that takes in the array and
*It is used to create a copy of the tree. *It can also be used to get the prefix the length of the array as parameters 3. In the func on, create a variable called “sorted” that is set to true
expression of an expression tree. 4. Create a for loop that iterates through the array star ng at index 0 and ending at the length of the array -1
Algorithm: *Un l all nodes of the tree are not visited 5. Within the for loop, compare the current element with the next element in the array. 6.If the current element is greater
*Step 1 - Visit the root node *Step 2 - Traverse the le subtree recursively. than the next element, swap their posi ons and set “sorted” to false 7.A er the for loop, check if “sorted” is false 8.If
* Step 3 - Traverse the right subtree recursively. “sorted” is false, call the “bubbleSort” func on again with the same array and length as parameters
Postorder traversal: This technique follows the 'le -right root' policy. It means 9.If “sorted” is true, the array is now sorted and the func on will return the sorted array 10.Call the “bubbleSort” func on with
that the first le subtree of the root node is traversed, a er that recursively the ini al unsorted array and its length as parameters to begin the sor ng process.
traverses the right subtree, and finally, the root node is traversed. As the root Quick Sort: Quick Sort is a popular and efficient sor ng algorithm that uses a divide-and-conquer approach to sort elements in
node is traversed a er (or post) the le and right subtree, it is called postorder an array or a list. It is an in-place comparison-based sor ng algorithm that has an average me complexity of O(n log n). The
traversal. So, in a postorder traversal, each node is visited a er both of its basic idea behind Quick Sort is to select a pivot element from the array and par on the other elements into two sub- arrays,
subtrees. We start from A, and following Post-order traversal, we first visit the le according to whether they are less than or greater than the pivot. The pivot element is then placed in its correct posi on in the
subtree B. B is also traversed post-order. The process goes on un l all the nodes sorted array, with all the elements to the le of the pivot being smaller than it and all the elements to the right being larger than
are visited. The output of post-order traversal of this tree will be − D → E → B → F it. This process is repeated recursively for the le and right sub-arrays un l the en re array is sorted.
→G→C→A The applica ons of postorder traversal include - *It is used to Algorithm: if (start < end) QUICKSORT (A, start, p - 1)
delete the tree. *It can also be used to get the pos ix expression of an expression tree. QUICKSORT (array A, start, end) { QUICKSORT (A, p + 1, end)
Algorithm:*Un l all nodes of the tree are not visited*Step 1 - Traverse the le subtree recursively. { p = par on(A, start, end) }}
*Step 2 - Traverse the right subtree recursively. *Step 3 - Visit the root node.
Inorder traversal: This technique follows the 'le root right' policy. It means Selec on Sort: In selec on sort, the smallest value among the unsorted elements of the array is selected in every pass and
that first le subtree is visited a er that root node is traversed, and finally, inserted to its appropriate posi on into the array. It is also the simplest algorithm. It is an in-place comparison sor ng algorithm.
the right subtree is traversed. As the root node is traversed between the le In this algorithm, the array is divided into two parts, first is sorted part, and another one is the unsorted part. Ini ally, the sorted
and right subtree, it is named inorder traversal. So, in the inorder part of the array is empty, and unsorted part is the given array. Sorted part is placed at the le , while the unsorted part is placed
traversal, each node is visited in between of its subtrees. We start from A, at the right. In selec on sort, the first smallest element is selected from the unsorted array and placed at the first
and following in-order traversal, we move to its le subtree B. B is also posi on. A er that second smallest element is selected and placed in the second posi on. The process con nues un l the array
traversed in-order. The process goes on un l all the nodes are visited. The is en rely sorted. The average and worst-case complexity of selec on sort is O(n2), where n is the number of items. Due to this, it
output of inorder traversal of this tree will be − D → B → E → A → F → C → G is not suitable for large data sets.
The applica ons of Inorder traversal includes -*It is used to get the BST Selec on sort is generally used when -*A small array is to be sorted *Swapping cost doesn't ma er
nodes in increasing order. *It can also be used to get the prefix expression of *It is compulsory to check all elements
an expression tree. Algorithm: [END OF LOOP] if (SMALL > arr[j])
Algorithm:*Un l all nodes of the tree are not visited.*Step 1 - Traverse the le subtree recursively. SELECTION SORT(arr, n) Step 4: EXIT SET SMALL = arr[j]
*Step 2 - Visit the root node. *Step 3 - Traverse the right subtree recursively. Step 1: Repeat Steps 2 and 3 for i = 0 to n- SMALLEST (arr, i, n, pos) SET pos = j
Stack: A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. Stack has one end, whereas the Queue 1 Step 1: [INITIALIZE] SET SMALL = arr[i] [END OF if]
has two ends (front and rear). It contains only one pointer top pointer poin ng to the topmost element of the stack. Whenever Step 2: CALL SMALLEST(arr, i, n, pos) Step 2: [INITIALIZE] SET pos = i [END OF LOOP]
an element is added in the stack, it is added on the top of the stack, and the element can be deleted only from the stack. In other Step 3: SWAP arr[i] with arr[pos] Step 3: Repeat for j = i+1 to n Step 4: RETURN pos
words, a stack can be defined as a container in which inser on and dele on can be done from the one end known as the top of the stack. Heap Sort: Heap Sort is a sor ng algorithm that uses a binary heap data structure to sort elements in an array. It is an in-place
Some key points related to stack: *It is called as stack because it behaves like a real-world stack, piles of books, etc. comparison-based sor ng algorithm with an average me complexity of O(n log n). The basic idea behind Heap Sort is to
*A Stack is an abstract data type with a pre-defined capacity, which means that it can store the elements of a limited size. *It is a first build a binary heap from the array of elements to be sorted. A binary heap is a tree-like data structure where the parent
data structure that follows some order to insert and delete the elements, and that order can be LIFO or FILO. node is always greater than its child nodes (in a max heap) or less than its child nodes (in a min heap). Once the binary heap is
The following are some common opera ons implemented on the stack: constructed, the maximum element (in a max heap) or minimum element (in a min heap) is extracted from the root of the heap
*push(): When we insert an element in a stack then the opera on is known as a push. If the stack is full then the overflow and placed at the end of the array. The heap is then updated to maintain the heap property, and the process is repeated for the
condi on occurs. *pop(): When we delete an element from the stack, the opera on is known as a pop. If the stack is empty remaining elements in the heap un l the en re array is sorted.
Heap Sort Algorithm: 1. First convert the array into heap data structure using heapify, then one by one delete the root node of Array Linked list
the Max-heap and replace it with the last node in the heap and then heapify the root of the heap. Repeat this process un l size
A linked list is a collec on of objects known as a node where
of heap is greater than 1. 2. Build a heap from the given input array. 3. Repeat the following steps un l the heap contains only An array is a collec on of elements of a similar data type.
node consists of two parts, i.e., data and address.
one element: a. Swap the root element of the heap (which is the largest element) with the last element of the heap. b.
Remove the last element of the heap (which is now in the correct posi on). c. Heapify the remaining elements of the heap. Linked list elements can be stored anywhere in the memory or
Array elements store in a con guous memory loca on.
4. The sorted array is obtained by reversing the order of the elements in the input array. randomly stored.
Merge Sort: Merge sort is similar to the quick sort algorithm as it uses the divide and conquer approach to sort the elements. It Array works with a sta c memory. Here sta c memory means The Linked list works with dynamic memory. Here, dynamic
is one of the most popular and efficient sor ng algorithm. It divides the given list into two equal halves, calls itself for the two that the memory size is fixed and cannot be changed at the run memory means that the memory size can be changed at the run
halves and then merges the two sorted halves. We have to define the merge() func on to perform the merging. The sub-lists me. me according to our requirements.
are divided again and again into halves un l the list cannot be divided further. Then we combine the pair of one element lists Linked list elements are dependent on each other. As each node
into two-element lists, sor ng them in the process. The sorted two-element pairs is merged into the four-element lists, and so on Array elements are independent of each other. contains the address of the next node so to access the next node,
un l we get the sorted list. we need to access its previous node.
Algorithm: step 3: perform merge func on. mergesort(array, le , mid)
Array takes more me while performing any opera on like Linked list takes less me while performing any opera on like
step 1: start if le > right mergesort(array, mid+1, right)
inser on, dele on, etc. inser on, dele on, etc.
step 2: declare array and le , right, mid return merge(array, le , mid, right)
variable mid= (le +right)/2 step 4: Stop Accessing any element in an array is faster as the element in an Accessing an element in a linked list is slower as it starts
sequen al search: Linear search is also called as sequen al search algorithm. It is the simplest searching algorithm. In Linear array can be directly accessed through the index. traversing from the first element of the linked list.
search, we simply traverse the list completely and match each element of the list with the item whose loca on is to be found. If In the case of an array, memory is allocated at compile- me. In the case of a linked list, memory is allocated at run me.
the match is found, then the loca on of the item is returned; otherwise, the algorithm returns NULL. Memory u liza on is inefficient in the array. For example, if the Memory u liza on is efficient in the case of a linked list as the
It is widely used to search an element from the unordered list, i.e., the list in which items are not sorted. The worst-case me size of the array is 6, and array consists of 3 elements only then memory can be allocated or deallocated at the run me
complexity of linear search is O(n). the rest of the space will be unused. according to our requirement.
The steps used in the implementa on of Linear Search are listed as follows - *First, we have to traverse the array elements
using a for loop. *In each itera on of for loop, compare the search element with the current array element, and - *If the
Stack Queue
element matches, then return the index of the corresponding array element. *If the element does not match, then move to
the next element. * If there is no match or the search element is not present in the given array, return -1. It follows the principle LIFO (Last In- First Out), It follows the principle FIFO (First In -First Out), which implies that the
Algorithm Step 3: repeat step 4 while i <= n set ii = i + 1 which implies that the element which is inserted last element which is added first would be the first element to be removed
would be the first one to be deleted. from the list.
Linear_Search(a, n, val) // 'a' is the given a Step 4: if a[i] == val [end of loop]
rray, 'n' is the size of given array, 'val' is th set pos = i Step 5: if pos = -1 It has only one end from which both the insertion and It has two ends, i.e., front and rear end. The front end is used for the
e value to search print pos print "value is not present in the array " deletion take place, and that end is known as a top. deletion while the rear end is used for the insertion.
Step 1: set pos = -1 go to step 6 [end of if] It contains only one pointer known as a top pointer. It contains two pointers front and rear pointer. The front pointer holds
Step 2: set i = 1 [end of if] Step 6: exit The top pointer holds the address of the last inserted or the address of the first element, whereas the rear pointer holds the
Binary Search: Binary search is the search technique that works efficiently on sorted lists. Hence, to search an element into some the topmost element of the stack. address of the last element in a queue.
list using the binary search technique, we must ensure that the list is sorted. It performs two operations, push and pop. The push It performs mainly two operations, enqueue and dequeue. The enqueue
Binary search follows the divide and conquer approach in which the list is divided into two halves, and the item is compared with operation inserts the element in a list while the pop operation performs the insertion of the elements in a queue while the
the middle element of the list. If the match is found then, the loca on of the middle element is returned. Otherwise, we search operation removes the element from the list. dequeue operation performs the deletion of the elements from the queue.
into either of the halves depending upon the result produced through the match. If top==-1, which means that the stack is empty. If front== -1 or front = rear+1, which means that the queue is empty.
Binary search can be implemented on sorted array elements. If the list elements are not arranged in a sorted manner, we have If top== max-1, this condition implies that the stack is
first to sort them. It is a more efficient searching algorithm than Sequen al Searching for sorted arrays, with a me complexity of If rear==max-1, this condition implies that the stack is full.
full.
O(log n). The algorithm works by comparing the target element with the middle element of the array. If they are equal, the It is of three types like priority queue, circular queue and double ended
search is complete and the algorithm returns the index of the middle element. If the target element is greater than the middle It does not have any types.
queue.
element, the algorithm repeats the search on the right half of the array. If the target element is less than the middle element, the
It has a simpler implementation. It has a comparatively complex implementation than a stack.
algorithm repeats the search on the le half of the array. This process is repeated un l the target element is found or un l the
interval is empty. A Stack is visualized as a vertical collection. A Queue is visualized as a horizontal collection.
Here are the basic steps for Binary Search: *Ini alize two pointers, one to the beginning of the array (le ) and one to the end of
the array (right). *While the le pointer is less than or equal to the right pointer, do the following: *Calculate the middle index of Linear search Binary search
the array. *Compare the middle element with the target element. *If they are equal, return the index of the middle element. The linear search starts searching from the first element and
*If the target element is greater than the middle element, update the le pointer to the middle index + 1 and repeat the search It finds the position of the searched element by finding the
compares each element with a searched element till the element
middle element of the array.
on the right half of the array. *If the target element is less than the middle element, update the right pointer to the middle index is not found.
- 1 and repeat the search on the le half of the array. *If the target element is not found in the array, return a "not found" value. In a linear search, the elements don't need to be arranged in The pre-condition for the binary search is that the elements
Here are the basic steps for Binary Search: *Ini alize two pointers, one to the beginning of the array (le ) and one to the end of sorted order. must be arranged in a sorted order.
the array (right). *While the le pointer is less than or equal to the right pointer, do the following: *Calculate the middle index of
The implementation of binary search is limited as it can be
the array. *Compare the middle element with the target element. *If they are equal, return the index of the middle element. The linear search can be implemented on any linear data structure
implemented only on those data structures that have two-way
Here are the basic steps for Binary Search: *Ini alize two pointers, one to the beginning of the array (le ) and one to the end of such as an array, linked list, etc.
traversal.
the array (right). *While the le pointer is less than or equal to the right pointer, do the following: *Calculate the middle index of
It is based on the sequential approach. It is based on the divide and conquer approach.
the array. *Compare the middle element with the target element. *If they are equal, return the index of the middle element.
Algorithm Step 2: repeat steps 3 and 4 while beg <=e else It is preferrable for the small-sized data sets. It is preferrable for the large-size data sets.
Binary_Search(a, lower_bound, upper_bo nd set beg = mid + 1 It is less efficient in the case of large-size data sets. It is more efficient in the case of large-size data sets.
und, val) // 'a' is the given array, 'lower_bo Step 3: set mid = (beg + end)/2 [end of if] In a linear search, the worst- case scenario for finding the In a binary search, the worst-case scenario for finding the
und' is the index of the first array element, Step 4: if a[mid] = val [end of loop] element is O(n). element is O(log2n).
'upper_bound' is the index of the last arra set pos = mid Step 5: if pos = -1 In a linear search, the best-case scenario for finding the first In a binary search, the best-case scenario for finding the first
y element, 'val' is the value to search print pos print "value is not present in the array" element in the list is O(1). element in the list is O(1).
Step 1: set beg = lower_bound, end = upp go to step 6 [end of if] It can be implemented on both a single and multidimensional
er_bound, pos = - 1 else if a[mid] > val Step 6: exit It can be implemented only on a multidimensional array.
array.
set end = mid - 1