Friday, August 16, 2024

Sorting( Selection Sort, Insertion Sort )

 Sorting

Insertion sort:

  It is a very simple sorting algorithm in which the sorted array (or list) is built one element at a time.

 Insertion sort works similar to the sorting of playing cards in hands. It is assumed that the first card is already sorted in the card game, and then we select an unsorted card. If the selected unsorted card is greater than the first card, it will be placed at the right side; otherwise, it will be placed at the left side. Similarly, all unsorted cards are taken and put in their exact place

The same approach is applied in insertion sort. The idea behind the insertion sort is that first take one element, iterate it through the sorted array. Although it is simple to use, it is not appropriate for large data sets as the time complexity of insertion sort in the average case and worst case is O(n2), where n is the number of items. Insertion sort is less efficient than the other sorting algorithms like heap sort, quick sort, merge sort, etc.

 

The simple steps of achieving the insertion sort are listed as follows 

Step 1 - If the element is the first element, assume that it is already sorted. Return 1. 

Step2 - Pick the next element, and store it separately in a key. 

Step3 - Now, compare the key with all elements in the sorted array. 

Step 4 - If the element in the sorted array is smaller than the current element, then move to the next element. Else, shift greater elements in the array towards the right. 

Step 5 - Insert the value.

Step 6 - Repeat until the array is sorted.



Working of Insertion sort Algorithm:

To understand the working of the insertion sort algorithm, let's take an unsorted array. It will be easier to understand the insertion sort via an example.

Let the elements of array are


Initially, the first two elements are compared in insertion sort.

Here, 31 is greater than 12. That means both elements are already in ascending order. So, for now, 12 is stored in a sorted sub-array.


Now, move to the next two elements and compare them.


Here, 25 is smaller than 31. So, 31 is not at correct position. Now, swap 31 with 25. Along with swapping, insertion sort will also check it with all elements in the sorted array.

For now, the sorted array has only one element, i.e. 12. So, 25 is greater than 12. Hence, the sorted array remains sorted after swapping






Now, two elements in the sorted array are 12 and 25. Move forward to the next elements that are 31 and 8.

Both 31 and 8 are not sorted. So, swap them.

Both 31 and 8 are not sorted. So, swap them.



After swapping, elements 25 and 8 are unsorted.


So, swap them.

Both 12 and 8 are not sorted.

So, swap them.


Now, the sorted array has three items that are 8, 12 and 25. Move to the next items that are 31 and 32.

 


Hence, they are already sorted. Now, the sorted array includes 8, 12, 25 and 31.

Move to the next elements that are 32 and 17.

17 is smaller than 32. So, swap them.


Swapping makes 31 and 17 unsorted. So, swap them too.


Now, swapping makes 25 and 17 unsorted. So, perform swapping again.

Now, the array is completely sorted.

Insertion sort complexity:

Time Complexity:

Best Case Complexity - It occurs when there is no sorting required, i.e. the array is already sorted. The best-case time complexity of insertion sort is O(n).

Average Case Complexity - It occurs when the array elements are in jumbled order that is not properly ascending and not properly descending. The average case time complexity of insertion sort is O(n2).

Worst Case Complexity - It occurs when the array elements are required to be sorted in reverse order. That means suppose you have to sort the array elements in ascending order, but its elements are in descending order. The worst-case time complexity of insertion sort is O(n2).


#include <stdio.h>  

  

void insert(int a[], int n) /* function to sort an aay with insertion sort */  

{  

    int i, j, temp;  

    for (i = 1; i < n; i++) {  

        temp = a[i];  

        j = i - 1;  

  

        while(j>=0 && temp <= a[j])  /* Move the elements greater than temp to one position ahead from their current position*/  

        {    

            a[j+1] = a[j];     

            j = j-1;    

        }    

        a[j+1] = temp;    

    }  

}  

  

void printArr(int a[], int n) /* function to print the array */  

{  

    int i;  

    for (i = 0; i < n; i++)  

        printf("%d ", a[i]);  

}  

  

int main()  

{  

    int a[] = { 12, 31, 25, 8, 32, 17 };  

    int n = sizeof(a) / sizeof(a[0]);  

    printf("Before sorting array elements are - \n");  

    printArr(a, n);  

    insert(a, n);  

    printf("\nAfter sorting array elements are - \n");    

    printArr(a, n);  

  

    return 0;  

}    

Advantages of Insertion Sort

·  It is easy to implement and efficient to use on small sets of data.

·  It can be efficiently implemented on data sets that are already substantially sorted.

· It performs better than algorithms like selection sort and bubble sort. Insertion sort algorithm is simpler than shell sort, with only a small trade-off in efficiency. It is over twice as fast as the bubble sort and almost 40 per cent faster than the selection sort.

· It requires less memory space (only O(1) of additional memory space).

· It is said to be online, as it can sort a list as and when it receives new elements.

****************************************************

Wednesday, August 14, 2024

DS ASSIGNMENT 2 & 1


 DS ASSIGNMENT -2

DATE OF SUBMISSION: 02-11-24

1. Define AVL tree? Convert the following diagrams into Balanced AVL trees


2. What are types of rotations performed while inserting an element into an AVL tree?

3.Construct a B-Tree of order 5 with the following elements. 52, 85, 94, 65, 74, 84, 37, 15, 19, 21, 62, 77, 99, 101, 137

4.How to perform insertion and deletion in Priority Queue? Explain with suitable examples.

5.Write the implementation of search operation in red black trees..









 DS ASSIGNMENT -1

DATE OF SUBMISSION: 28-08-2024


  1. A)What are the postfix and prefix forms of the given below expression? A+B*(CD)/(P-R)? B) Convert the infix (a+b)*(c+d)/f  into postfix & prefix expression

  2. Explain the insertion operation in linked list. How nodes are inserted after a specified node? Define ADT and Mention the features of ADT.
  3. Give the trace of searching for 5 in the list of elements: 2, 5, 8, 10, 11, 15, 32, 64,78, 89 using binary search. Write the algorithm?
  4. What is Hash function? What are its types? How can we handle the collision using separate chaining and analyze its performance?
  5. A)Explain the operations of binary search tree with an example.
B) Construct a binary tree for the following sequence of numbers 45, 32, 90, 34, 68, 72, 15, 24 Traverse the binary tree created in order.

Monday, August 12, 2024

SEARCHING

 SEARCHING

The process of finding the location of a specific data item or record with a given key value or finding the locations of all records, which satisfy one or more conditions in a list, is called "Searching". If the item exists in the given list then search is said to be successful otherwise if the element if not found in the given list then search is said to be unsuccessful.

There are two popular methods for searching the array elements: linear search and binary search.


Linear Search:

Linear search is also called as sequential search algorithm. It is the simplest searching algorithm. In Linear search, we simply traverse the list completely and match each element of the list with the item whose location is to be found. If the match is found, then the location of the item is returned; otherwise, the algorithm returns NULL.

The steps used in the implementation of Linear Search are listed as follows -


  • First, we have to traverse the array elements using a for loop.
  • In each iteration of for loop, compare the search element with the current array element, and -
    • If the 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.

Now, let's see the algorithm of linear search.


To understand the working of linear search algorithm, let's take an unsorted array. It will be easy to understand the working of linear search with an example.

Let the elements of array are -

Now, start from the first element and compare K with each element of the array.


The value of K, i.e., 41, is not matched with the first element of the array. So, move to the next element. And follow the same process until the respective element is found.


Now, the element to be searched is found. So algorithm will return the index of the element matched.

Linear Search complexity:

The algorithm is called linear search because it's complexity/efficiency can be expressed as a linear function ie., the number of comparisons to find a target increases linearly as the size of the data. 
Linear search provide complexity for finding an element in an array because linear search is a step-by-step process, in which specific element is compared with each element of array.

Best Case

In the best case, the desired element is present in the first position of the array, Le, only one comparison is made. So T(n) = O (1).

Average Case

Here we asume that ITEM does appear, and that is equally likely to occur at any position in the array. Accordingly the number of comparisons can be any of the number 1, 2, 3, n and each number occurs with the probability p = 1 / n 
Then T(n)     =1. (1 / n) +2.(1/n)+3.(1/n)...+n.(1/n).
 =( 1 + 2 + 3 +...+n).(1/n)
 =n. (n + 1) /2.(1/n)
 = (n + 1) / 2
 = O((n + 1) / 2)

Worst Case

Clearly the worst case occurs when ITEM is the last element is the array or is not there at all. In either situation we have T(n) = n + 1 Accordingly T(n) = O(n + 1) is the worst case complexity of the linear search algorithm.



#include <stdio.h>  
int linearSearch(int a[], int n, int val) 
{  
  // Going through array sequencially  
  for (int i = 0; i < n; i++)  
    {  
        if (a[i] == val)  
        return i+1;  
    }  
  return -1;  
}  
int main() 
{  
  int a[] = {70, 40, 30, 11, 57, 41, 25, 14, 52}; // given array  
  int val = 41; // value to be searched  
  int n = sizeof(a) / sizeof(a[0]); // size of array  
  int res = linearSearch(a, n, val); // Store result  
  printf("The elements of the array are - ");  
  for (int i = 0; i < n; i++)  
  printf("%d ", a[i]);   
  printf("\nElement to be searched is - %d", val);  
  if (res == -1)  
  printf("\nElement is not present in the array");  
  else  
  printf("\nElement is present at %d position of array", res);  
  return 0;  
}  
Output:




  • Unsorted Lists: When we have an unsorted array or list, linear search is most commonly used to find any element in the collection.
  • Small Data Sets: Linear Search is preferred over binary search when we have small data sets with
  • Searching Linked Lists: In linked list implementations, linear search is commonly used to find elements within the list. Each node is checked sequentially until the desired element is found.
  • Simple Implementation: Linear Search is much easier to understand and implement as compared to Binary Search or Ternary Search.
  • Linear search can be used irrespective of whether the array is sorted or not. It can be used on arrays of any data type.
  • Does not require any additional memory.
  • It is a well-suited algorithm for small datasets.
  • Linear search has a time complexity of O(N), which in turn makes it slow for large datasets.
  • Not suitable for large arrays.

Saturday, August 10, 2024

DS IMP QUESTION

linked list

  1. Explain the insertion operation in linked list. How nodes are inserted after a specified node?
  2. Define ADT and Mention the features of ADT.
  3. Discuss the merge operation in circular linked lists.
  4. When doubly linked list can be represented as circular linked list? Mention the merits and demerits of linked list.
  5. What are the postfix and prefix forms of the given below expression? A+B*(CD)/(P-R)
  6. List three examples that uses linked list. What are the merits and demerits of array implementation of lists?
  7. Convert the infix (a+b)*(c+d)/f  into postfix & prefix expression
  8. What are the draw backs of single linked list? Write and explain the algorithm for search and modify operations in doubly linked list with example.
  9. Write a program to reverse the given single linked list with starting node as ‘head’.
  10. Write a program to implement stack using linked list.
  11. Write a program to insert, delete and print the elements using doubly linked list.
  12. Explain how to find whether the single linked list contains a loop?
  13. Write a pseudo code for it. Assume the single linked list is having initial node as ‘head’.
  14. What are the operations of Circular linked list? List its applications in computer science.
  15. Write a program to reverse the given single linked list with starting node as ‘head’.
  16. Write an algorithm to delete an element anywhere from double linked list.
  17. Explain the operations on single linked lisT 


 

queue.

  1. Write the routine to insert an element into a queue. Write the routine for insertion operation of singly linked list
  2. A circular queue has a size of 5 and has 3 elements 10,20 and 40 where F=2 and R=4. After inserting 50 and 60, what is the value of F and R. Trying to insert 30 at this stage what happens? Delete 2 elements from the queue and insert 70, 80 & 90.Explain and also show the sequence of steps with necessary diagrams with the value of F & R
  3. What is a DeQueue? Explain its operation with example
  4.  
  5. What are the limitations of queue? Explain the algorithms for various operations of circular queue
  6.  What are the applications of queue? Write a routine for IsEmpty condition of queue.
  7.  What are enqueue and dequeue operations?
  8. Write a program to implement queue using linked list
  9. Explain how can we find the number of nodes in a single linked list? Write a pseudo code for it.
  10. Write a program to implement queue using arrays.
  11. What is a queue? Write an algorithm for implementing queue using linked list

 

stack

  1. Mention any four applications of stack.
  2.  Define an efficient representation of two stacks in a given area of memory with n words and explain
  3. What are the features of stacks?
  4.  Explain the usage of stack in recursive algorithm implementation?
  5. What are the operations of stack? List its applications in computer science.
  6. How can we find the address of a second node from the end in a single linked list? Write pseudo code for it.
  7.  What are the operations of Queue? List its applications in computer science. Write a program.
  8.  Write a program to implement single linked list with starting node as ‘head’.
  9.  Write a program to insert an element into a single linked list by considering all the possible cases.
  10. What is a stack? Explain how it can be useful in evaluating expressions with suitable examples
  11.  Write a program to implement stack using arrays.
  12. Explain the stack data structure with suitable example. Give algorithms FOR Push, Pop operations

MID-2  IMP QUESTION

  1. Compare full and complete binary tree with examples.Compare linear search and binary search. SOLUTION
  2. Construct a binary search tree with the following elements and determine its height. 15, 84, 7, 91, 3, 6, 41, 1, 25, 21, 32, 37, 45, 5, 9 SOLUTION
  3. Explain how a node with both the children can be deleted from a binary search tree with suitable examples. SOLUTION
  4. Explain the Four Rotations used to convert an unbalanced BST into Balanced AVL Tree.  SOLUTION
  5. Construct a B-Tree of order 5 with the following elements.37, 15, 19, 21, 62, 77, 99, 52, 85, 94, 65, 74, 84, 121 SOLUTION
  6. Construct the Red-Black Tree for the set of data values {10, 18, 7, 15, 16, 30} and also mention the step-by-step procedure. SOLUTION
  7. What is priority Queue? How can priority queues can be implemented? Explain in brief  SOLUTION
  8. What is a Splay tree? How it is different from binary search tree? List any two applications of splay trees. SOLUTION1    SOLUTION2

 

Thursday, August 8, 2024

QUEUE

 QUEUE

Queue is linear data structure and collection of elements. A queue is another special kind of list, where items are inserted at one end called the rear and deleted at the other end called the front. 

  • The principle of queue is a “FIFO” or “First-in-first-out”.
  • Queue is an abstract data structure. 
  • A queue is a useful data structure in programming. 
  • It is similar to the ticket queue outside a cinema hall, where the first person entering the queue is the first person who gets the ticket.
A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first.
More real-world examples can be seen as queues at the ticket windows and bus-stops and our college library.

Operations on QUEUE:
A queue is an object or more specifically an abstract data structure (ADT) that allows the following operations: 
• Enqueue or insertion: which inserts an element at the end of the queue. 
• Dequeue or deletion: which deletes an element at the start of the queue.
Representation of Queue (or) Implementation of Queue: 
The queue can be represented in two ways: 
1. Queue using Array             2. Queue using Linked List




Applications of Queue

Due to the fact that queue performs actions on first in first out basis which is quite fair for the ordering of actions. There are various applications of queues discussed as below.

  1. Queues are widely used as waiting lists for a single shared resource like printer, disk, CPU.
  2. Queues are used in asynchronous transfer of data (where data is not being transferred at the same rate between two processes) for eg. pipes, file IO, sockets.
  3. Queues are used as buffers in most of the applications like MP3 media player, CD player, etc.
  4. Queue are used to maintain the play list in media players in order to add and remove the songs from the play-list.
  5. Queues are used in operating systems for handling interrupts.

STLD QUESTION BANK & SOLUTION

 STLD mid-1 solution https://docs.google.com/document/d/1RkU6RE-COZCG_MY4oCihimX4muc9jJM9/edit?usp=drivesdk&ouid=102051422039972401246...