Data Structure - GTU Paper Solution (SEM 3)

Q-1) Explain primitive and Non-primitive data types in detail.

Ans> Primitive Data Structure are those data structures that hold a single value in a specific location.
  • Also Primitive Data Structures are the basic data structures that directly operate upon the machine instructions.
  • They have different representations on different computers.
  • Integers, Floating point numbers, Character constants, String constants and Pointers come under this category.
Non-primitive data structures are more complicated data structures and are derived from primitive data structures.
  • They emphasize on grouping same or different data items with relationship between each data item.
  • Arrays, Lists and Files come under this category.

Primitive data structure:
  • Primitive data structure is a kind of data structure that stores the data of only one type.
  • Examples of primitive data structure are integer, character, float.
  • Primitive data structure will contain some value, i.e., it cannot be NULL.
  • The size depends on the type of the data structure.
  • It starts with a lowercase character.
  • Primitive data structure can be used to call the methods.
Non-primitive data structure:
  • Non-primitive data structure is a type of data structure that can store the data of more than one type.
  • Examples of non-primitive data structure are Array, Linked list, stack.
  • Non-primitive data structure can consist of a NULL value.
  • In case of non-primitive data structure, size is not fixed
  • It starts with an uppercase character.
  • Non-primitive data structure cannot be used to call the methods.


Q-2) Explain Binary Search with example.

Ans> Binary search is the search technique that works efficiently on sorted lists. Hence, to search an element into some list using the binary search technique, we must ensure that the list is sorted.
  • Binary search follows the divide and conquer approach in which the list is divided into two halves, and the item is compared with the middle element of the list. If the match is found then, the location of the middle element is returned. Otherwise, we search into either of the halves depending upon the result produced through the match.
  • Binary Search Approach: Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half.
Binary Search Algorithm: We basically ignore half of the elements just after one comparison.
  • In Binary search each time we divide array in to two equal part and compare middle element with the search element
  • If the middle element is equal to search element then we got the location of sreach element and return index of that.
  • Else If Serach element is greater than the mid element, then search element can only lie in the right half subarray after the mid element. So we recur for the right half.
  • Else (x is smaller) recur for the left half.
Example : Find 6 in (1,5,6,18,19,25,45,78)

Step 1) Comparing Search element(6) with middle element(18 or 19).
Here, 6<18
So we Search for the left half(1,5,6).

Step 2) Again Comparing Search element(6) with middle element(5) of left half(1,5,6)
Here,6>5
so we look for right to the middle element, as search element is greater than middle element.

Step 3)Hence, the remaining element is only one that is 6 which match with our search element.We found it ,so write its Index number which was the main aim of this search operation.
So the , Index(6)=2


Pictorial Representation of Another Example : 





Q-3) Explain Asymptotic Notations in detail. 

Ans> Asymptotic Notation is used to describe the running time of an algorithm - how much time an algorithm takes with a given input, n. There are three different notations: 
  • Big O, 
  • Big Theta (Θ), and 
  • Big Omega (Ω). 

Big O:
  •  for the worst case running time



Big Theta (Θ):
  • Big-Θ is used when the running time is the same for all cases


 
Big Omega (Ω):
  • for the best case running time.


Q-4) Differentiate: Static and Dynamic Memory Allocation.
Ans> 

Static Memory Allocation:
  • In the static memory allocation, variables get allocated permanently, till the program executes or function call finishes.
  • Static Memory Allocation is done before program execution.
  • It uses stack for managing the static allocation of memory.
  • It is less efficient.
  • In Static Memory Allocation, there is no memory re-usability
  • In static memory allocation, once the memory is allocated, the memory size can not change.
  • In this memory allocation scheme, we cannot reuse the unused memory.
  • In this memory allocation scheme, execution is faster than dynamic memory allocation.
  • In this memory is allocated at compile time.
  • In this allocated memory remains from start to end of the program.
  • Example: This static memory allocation is generally used for array.

Dynamic Memory Allocation

  • In the Dynamic memory allocation, variables get allocated only if your program unit gets active.
  • Dynamic Memory Allocation is done during program execution.
  • It uses heap for managing the dynamic allocation of memory.
  • It is more efficient.
  • In Dynamic Memory Allocation, there is memory re-usability and memory can be freed when not required.
  • In dynamic memory allocation, when memory is allocated the memory size can be changed.
  • This allows reusing the memory. The user can allocate more memory when required. Also, the user can release the memory when the user needs it.
  • In this memory allocation scheme, execution is slower than static memory allocation.
  • In this memory is allocated at run time.
  • In this allocated memory can be released at any time during the program.
  • Example: This dynamic memory allocation is generally used for linked list.

Q-4) Explain linear and Non-linear data structure with example.
Ans> 

Linear Data Structure :
  • Data structure where data elements are arranged sequentially or linearly where the elements are attached to its previous and next adjacent  is called a linear data structure.
  • In linear data structure, single level is involved. Therefore, we can traverse all the elements in single run only.
  • Linear data structures are easy to implement because computer memory is arranged in a linear way.
  • Its examples are array, stack, queue, linked list, etc. 

Array:
  • The array is a type of data structure that stores elements of the same type.
  • These are the most basic and fundamental data structures. Data stored in each position of an array is given a positive value called the index of the element. The index helps in identifying the location of the elements in an array.
  • If supposedly we have to store some data i.e. the price of ten cars, then we can create a structure of an array and store all the integers together. This doesn’t need creating ten separate integer variables. Therefore, the lines in a code are reduced and memory is saved. The index value starts with 0 for the first element in the case of an array

Non-linear Data Structure: 
  • Data structures where data elements are not arranged sequentially or linearly are called non-linear data structures.
  • In a non-linear data structure, single level is not involved.Therefore, we can’t traverse all the elements in single run only.
  • Non-linear data structures are not easy to implement in comparison to linear data structure. It utilizes computer memory efficiently in comparison to a linear data structure.
  • Its examples are trees and graphs.  

Tree :
  • A tree data structure consists of various nodes linked together.
  • The structure of a tree is hierarchical that forms a relationship like that of the parent and a child.
  • The structure of the tree is formed in a way that there is one connection for every parent-child node relationship.Only one path should exist between the root to a node in the tree.
  • Various types of trees are present based on their structures like AVL tree, binary tree, binary search tree, etc.

Q-5) What is stack? Explain operations on stack in detail.
Ans> 
  • Stack is a linear data structure in which elements are stored in linear or sequential manner. 
  • The Insertion and deletion operation are performed at the one end only.
  • Stack follow LIFO(last In First Out) Principal.


  • In a stack, the top element is the element that is inserted at the last or most recently inserted element.

Opeartions On Stack :

1) Push : 
  • It is an process or opeation to insert or enter data in stack.
  • Since There is only one postion or element to insert data in stack using TOP element.

2) POP : 
  • It is an process to remove element from stack.
  • Deletion of element or data always done from the TOP or Same end where the insertion already done.
3) PEEK :
  • It prints or allow user to see the element of the stack at TOP. 
  • OR, It prints TOP Element of Stack.
4) isEmpty : Check if stack is empty or not

5) isFull : Check if stack is full or not


Q-6) What is queue? Explain operations on queue in detail.
Ans>
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at both its ends. One end is always used to insert data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first.

Opeations on Queue :



1) enqueue() − add (store) an item to the queue.

int enqueue(int data)      
   if(isfull())
      return 0;
   
   rear = rear + 1;
   queue[rear] = data;
   
   return 1;
end procedure

2) dequeue() − remove (access) an item from the queue.

int dequeue() {
   if(isempty())
      return 0;

   int data = queue[front];
   front = front + 1;

   return data;
}

3) peek() − Gets the element at the front of the queue without removing it.

int peek() {
   return queue[front];
}

4) isfull() − Checks if the queue is full.

stack isfull() {
   if(rear == MAXSIZE - 1)
      return true;
   else
      return false;
}

5) isempty() − Checks if the queue is empty.

stack isempty() {
   if(front < 0 || front > rear) 
      return true;
   else
      return false;
}

In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing (or storing) data in the queue we take help of rear pointer.


Q-7) Explain advantages of circular queue over Simple queue.
Ans>
Simple Queue: A Simple Queue is generally referred to as Queue. It is a linear data structure that follows the FIFO (First In First Out) order. In Queue all deletions (dequeue) are made at the front and all insertions (enqueue) are made at the rear end.



Circular Queue: Circular Queue is just a variation of the linear queue in which front and rear-end are connected to each other to optimize the space wastage of the Linear queue and make it efficient.



Below are the operations that will illustrate that how is Circular Queue is better than Linear Queue:
  • When Enqueue operation is performed on both the queues: Let the queue is of size 6 having elements {29, 21, 72, 13, 34, 24}. In both the queues the front points at the first element 29 and the rear points at the last element 24 as illustrated below:


  • When the Dequeue operation is performed on both the queues: Consider the first 2 elements that are deleted from both the queues. In both the queues the front points at element 72 and the rear points at element 24 as illustrated below:


  • Now again enqueue operation is performed: Consider an element with a value of 100 is inserted in both the queues. The insertion of element 100 is not possible in Linear Queue but in the Circular Queue, the element with a value of 100 is possible as illustrated below:



Explanation:
  • As the insertion in the queue is from the rear end and in the case of Linear Queue of fixed size insertion is not possible when rear reaches the end of the queue.
  • But in the case of Circular Queue, the rear end moves from the last position to the front position circularly.
Conclusion: The circular queue has more advantages than a linear queue. Other advantages of circular queue are:

Easier for insertion-deletion: In the circular queue, elements can be inserted easily if there are vacant locations until it is not fully occupied, whereas in the case of a linear queue insertion is not possible once the rear reaches the last index even if there are empty locations present in the queue.

Efficient utilization of memory: In the circular queue, there is no wastage of memory as it uses the unoccupied space, and memory is used properly in a valuable and effective manner as compared to a linear queue.

Ease of performing operations: In the linear queue, FIFO is followed, so the element inserted first is the element to be deleted first. This is not the scenario in the case of the circular queue as the rear and front are not fixed so the order of insertion-deletion can be changed, which is very useful.


Q-7) Explain Tower Of Hanoi with example.
Ans>

Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. 




Tower of Hanoi puzzle with n disks can be solved in minimum 2^(n)−1 steps. This presentation shows that a puzzle with 3 disks has taken 
2^(3) - 1 = 7 steps.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 

  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  • No disk may be placed on top of a smaller disk.

Q-8) Write and explain algorithm for deletion in Singly Linked List.
Ans>
To delete a node from the linked list, we need to do the following steps:
 
1) Find the previous node of the node to be deleted. 
2) Change the next of the previous node. 
3) Free memory for the node to be deleted.

Algorithm for Deletion :

  • Step 1:
    IF HEAD = NULL
    Write UNDERFLOW
    Go to Step 5
  • Step 2: SET PTR = HEAD
  • Step 3: SET HEAD = HEAD -> NEXT
  • Step 4: FREE PTR
  • Step 5: EXIT

1. Delete from beginning

  • Point head to the second node
head = head->next;

2. Delete from end

    • Traverse to second last element
    • Change its next pointer to null

      struct node* temp = head;
      while(temp->next->next!=NULL){
        temp = temp->next;
      }
      temp->next = NULL;

      3. Delete from middle

      • Traverse to element before the element to be deleted
      • Change next pointers to exclude the node from the chain
      for(int i=2; i< position; i++) {
        if(temp->next!=NULL) {
          temp = temp->next;
        }
      }
      
      temp->next = temp->next->next;



      Q-9) Evaluate the following postfix expression in tabular form: 3 5 * 6 2 / +
      Ans>

      (Scanned Symbol)(Stack)
      3 3
      5 3,5
      * 15
      6 15,6
      2 15,6,2
      / 15,3
      + 18


      Q-10) Explain Dequeue and Priority queue in detail.
      Ans>
      Priority Queue : A queue is termed as a priority queue if it has the following characteristics:
      • Each item has some priority associated with it.
      • An item with the highest priority is moved at the front and deleted first.
      • If two elements share the same priority value, then the priority queue follows the first-in-first-out principle for de queue operation.

      A priority queue is of two types :

      1) Ascending Order Priority Queue :
      In the above table, 4 has the highest priority, and 45 has the lowest priority.

      An ascending order priority queue gives the highest priority to the lower number in that queue. For example, you have six numbers in the priority queue that are 4, 8, 12, 45, 35, 20. Firstly, you will arrange these numbers in ascending order. The new list is as follows: 4, 8, 12, 20. 35, 45. In this list, 4 is the smallest number. Hence, the ascending order priority queue treats number 4 as the highest priority.

      4 8 12 20 35 45

      2) Descending Order Priority Queue :
      A descending order priority queue gives the highest priority to the highest number in that queue. For example, you have six numbers in the priority queue that are 4, 8, 12, 45, 35, 20. Firstly, you will arrange these numbers in ascending order. The new list is as follows: 45, 35, 20, 12, 8, 4. In this list, 45 is the highest number. Hence, the descending order priority queue treats number 45 as the highest priority.

      45 35 20 12 8 4
      In the above table, 4 has the lowest priority, and 45 has the highest priority.

      Dequeue :

      A deque is also a special type of queue. In this queue, the enqueue and dequeue operations take place at both front and rear. That means, we can insert an item at both the ends and can remove an item from both the ends. Thus, it may or may not adhere to the FIFO order:

      Further, it has two special cases: input-restricted deque and output-restricted deque
      1) Input restricted Dequeue :
      the enqueue operation takes place only at the rear, but the dequeue operation takes place at both rear and front:

      An input-restricted queue is useful when we need to remove an item from the rear of the queue.

      2) Output restricted Dequeue :

      In the second case, the enqueue operation takes place at both rear and front, but the dequeue operation takes place only at the front:

      An output-restricted queue is handy when we need to insert an item at the front of the queue.


      Q-11) Define the following:
      1. Sibling
      2. Forest
      3. Strictly Binary Tree
      Ans>
      1. Sibling : In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In simple words, the nodes with the same parent are called Sibling nodes.
      2. Forest Forest is a collection of disjoint trees. In other words, we can also say that forest is a collection of an acyclic graph which is not connected. Here is a pictorial representation of a forest.

      Here you can see that there is no connected tree in the example. A single tree and empty graph is also an example of forest data structure.

      3. Strictly binary Tree : also known as a full binary tree. The tree can only be considered as the full binary tree if each node must contain either 0 or 2 children. The full binary tree can also be defined as the tree in which each node must contain 2 children except the leaf nodes.

      In the above example of a tree, we can observe that each node is either containing zero or two children; therefore, it is a Full Binary tree or strictly binary tree.


      Q-12) Write an algorithm for selection sort.

      Ans>Selection sort is another sorting technique in which we find the minimum element in every iteration and place it in the array beginning from the first index. 
      Steps involved in Selection Sort :
      1. Find the smallest element in the array and swap it with the first element of the array i.e. a[0].
      2. The elements left for sorting are n-1 so far. Find the smallest element in the array from index 1 to n-1 i.e. a[1] to a[n-1] and swap it with a[1].
      3. Continue this process for all the elements in the array until we get a sorted list.
      Algorithm :
      Step 1 − Set MIN to location 0
      Step 2 − Search the minimum element in the list
      Step 3 − Swap with value at location MIN
      Step 4 − Increment MIN to point to next element
      Step 5 − Repeat until list is sorted

      Q-12) Differentitae: BFS and DFS.
      Ans>
      Breadth First Search
      BFS stands for Breadth First Search is a vertex based technique for finding a shortest path in graph. It uses a Queue data structure which follows first in first out. In BFS, one vertex is selected at a time when it is visited and marked then its adjacent are visited and stored in the queue. It is slower than DFS. 
      Ex- 
              A
             / \
            B   C
           /   / \
          D   E   F
      Output is: 
      A, B, C, D, E, F

      Depth First Search
      DFS stands for Depth First Search is a edge based technique. It uses the Stack data structure, performs two stages, first visited vertices are pushed into stack and second if there is no vertices then visited vertices are popped. 
      Ex- 
              A
             / \
            B   C
           /   / \
          D   E   F
      Output is: 
      A, B, D, C, E, F

      S.NOBFSDFS
      1
      • BFS stands for Breadth First Search.
      • DFS stands for Depth First Search.
      2
      • BFS(Breadth First Search) uses Queue data structure for finding the shortest path.
      • DFS(Depth First Search) uses Stack data structure.
      3
      • BFS can be used to find single source shortest path in an unweighted graph, because in BFS, we reach a vertex with minimum number of edges from a source vertex.
      • In DFS, we might traverse through more edges to reach a destination vertex from a source.
      4
      • BFS is more suitable for searching vertices which are closer to the given source.
      • DFS is more suitable when there are solutions away from source.
      5
      • BFS considers all neighbors first and therefore not suitable for decision making trees used in games or puzzles.
      • DFS is more suitable for game or puzzle problems. We make a decision, then explore all paths through this decision. And if this decision leads to win situation, we stop.
      6
      • The Time complexity of BFS is O(V + E) when Adjacency List is used and O(V^2) when Adjacency Matrix is used, where V stands for vertices and E stands for edges.
      • The Time complexity of DFS is also O(V + E) when Adjacency List is used and O(V^2) when Adjacency Matrix is used, where V stands for vertices and E stands for edges.
      7
      • Here, siblings are visited before the children




      • Here, children are visited before the siblings



       
       
       
      Q-13) Explain Kruskal’s algorithm with suitable example.
      Ans>

      Kruskal's algorithm to find the minimum cost spanning tree uses the greedy approach. This algorithm treats the graph as a forest and every node it has as an individual tree. A tree connects to another only and only if, it has the least cost among all available options and does not violate MST properties.

      To understand Kruskal's algorithm let us consider the following example −

      MST Graph

      Step 1 - Remove all loops and Parallel Edges

      Remove all loops and parallel edges from the given graph.

      MST Graph with loops

      In case of parallel edges, keep the one which has the least cost associated and remove all others.

      MST Graph without loops

      Step 2 - Arrange all edges in their increasing order of weight

      The next step is to create a set of edges and weight, and arrange them in an ascending order of weightage (cost).

      MST ascending weightage

      Step 3 - Add the edge which has the least weightage

      Now we start adding edges to the graph beginning from the one which has the least weight. Throughout, we shall keep checking that the spanning properties remain intact. In case, by adding one edge, the spanning tree property does not hold then we shall consider not to include the edge in the graph.

      MST Graph step one

      The least cost is 2 and edges involved are B,D and D,T. We add them. Adding them does not violate spanning tree properties, so we continue to our next edge selection.

      Next cost is 3, and associated edges are A,C and C,D. We add them again −

      MST Graph step two

      Next cost in the table is 4, and we observe that adding it will create a circuit in the graph. −

      MST Graph step three

      We ignore it. In the process we shall ignore/avoid all edges that create a circuit.

      MST Graph step four

      We observe that edges with cost 5 and 6 also create circuits. We ignore them and move on.

      MST Graph step five

      Now we are left with only one node to be added. Between the two least cost edges available 7 and 8, we shall add the edge with cost 7.

      MST Kruskals Algorithm

      By adding edge S,A we have included all the nodes of the graph and we now have minimum cost spanning tree.

      Q-13) Explain indexed file organization.

      An indexed file contains records ordered by a record key. A record key uniquely identifies a record and determines the sequence in which it is accessed with respect to other records.

      Each record contains a field that contains the record key. A record key for a record might be, for example, an employee number or an invoice number.

      An indexed file can also use alternate indexes, that is, record keys that let you access the file using a different logical arrangement of the records. For example, you could access a file through employee department rather than through employee number.

      The possible record transmission (access) modes for indexed files are sequential, random, or dynamic. When indexed files are read or written sequentially, the sequence is that of the key values.

      Q-14)Explain rotation rules for AVL tree.

      AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes.
      The balance factor of a node is the difference in the heights of the left and right subtrees. The balance factor of every node in the AVL tree should be either +1, 0 or -1.
      Rotation Techniques
      1. Left Rotation (LL Rotation)
      2. Right Rotation (RR Rotation)
      3. Left-Right Rotation (LR Rotation)
      4. Right-Left Rotation (RL Rotation)

       

      Left Rotation :

       

       

      Right Rotation :

       

       

      Left-Right Rotation :

       

       

      Right-Left Rotation :

       

       

      Post a Comment

      Previous Post Next Post

      Contact Form