You are on page 1of 104

DSA LAB FILE

III-rd SEMESTER 2021

NAME – MUDRAX DAGAR


ROLL NO. – 2K20/CO/281
Experiment 1- STRING LIBRARY
1.1.

Aim-to find length of string

Input-

input a string type of input

output-

length of string we have input

Algorithm-Each string contains a null at end so we iterate till the character is null updating the value of
length by 1 every time it moves ahead,then when iterator points to null we return length.

Flowchart
Code-

#include <iostream.h>
int main()
{
char s[100];
int i;

printf(“Enter a string: “);
scanf(“%s”, s);

for(i = 0; s[i] != ‘\0’; ++i);

printf(“Length of string: %d”, i);
return 0;
}

Output for diff inputs-

Conclusion-
We have calculated length of string using the method of accessing elements of string.

Learning-

We learnt to access an element of the string and computed its length which is number of elements in
string including the spaces and special characters.

1.2.

aim-to concatenate 2 strings

input-

input string 1

input string 2

output-

concatenated string

algorithm-Take a string and iterate over first string and push its element into a empty string.Now iterate
over the second string and push its characters into the same string in which first strings's character were
pushed.

flowchart-
code-

#include<bits/stdc++.h>
using namespace std;

 bool subset(string a, string b) {
      if(a == b)
      return true;
      int j = 0;
      for(int i = 0; i < b.size(); i++){
         if(a[j] == b[i])
         {j++;}
         if(j == a.size())
        {

        return true;}
      }
      return false;
   }

int length(string s)
{
    int cnt=0;
    for(int i=0;s[i]!='\0';i++)
    {

        cnt++;
    }

     return cnt;
}
   void compare(string a,string b)
   {
    int i=0;
       if(length(a)==length(b))
       {
           if(a==b)
           {

               cout<<"equal";
               return;
           }
           while(a[i]!='\0')
           {
               if(a[i]>b[i])
               {
                   cout<<"a>b";
                   return;
               }
               else if(a[i]<b[i])
               {
                   cout<<"b>a";
                   return;
               }
               else if(a[i]==b[i])
               {
                   i++;
               }
           }

       }
       else if(length(a)!=length(b)){
        int i=0;
        int j=0;
        while(a[i]!='\0'&&b[j]!='\0')
        {
            if(a[i]>b[j])
            {
                cout<<"a>b";
                break;
                return;

            }
            else if(a[i]<b[j]){
                    cout<<"b>a";
                    break;
                    return;

            }
            else if(a[i]==b[j])
            {
                i++;
                j++;

            }

        }
        if(subset(b,a)||subset(a,b))
        {if(length(a)>length(b))
        {
            cout<<"a>b";
        }
        else{
            cout<<"b>a";
        }}
       }

   }
bool palindrome(string s)
{

bool flag;
int i=0;
int j=length(s)-1;

    while(i<j){
        if(s[i]==s[j])
        {
            flag=true;
        }
        else
        {
             flag=false;
        }
        i++;
        j--;}

   return flag;
}
string concatenate(string &a,string &b)
{
    string s;

    for(int i=0;i<length(a);i++)
    {
        s.push_back(a[i]);

    }
    for(int i=0;i<length(b);i++)
    {

        s.push_back(b[i]);
    }
    return s;

}
int main()
{
    string s;
    cin>>s;
    cout<<length(s);
    if(palindrome(s))
    {
        cout<<"yes palindrome";
   }
   else{
        cout<<"not palindrome";
    }
    string a;
    cin>>a;
    if(subset(s,a))
    {
        if s is a subset of a
        cout<<"yes subset"<<endl;
    }
    else{
        cout<<"not subset"<<endl;
   }

    //cout<<length(s);
    string b;
    cin>>b;
    cout<<concatenate(s,b);
    compare(s,b);

    return 0;

outputs for different inputs-

conclusion-
We hence concatenated 2 strings together by using length function already built by us and pushing both
strings together into a new string and returning the new string.

Learning-

We have accessed a string and added another at the end of it without making any new string.

1.3.

objective-To check if a string is a palindrome

input-

input string to be checked

output-

if a palindrome then yes a palindrome is printed else not palindrome is not printed.

algorithm-We take 2 pointers one at start and one at end of string then compare the 2 pointers. A
palindrome should have same characters at both ends since    it reads same from both sides if we start
from either left or right its same .So we compare both pointers if they are same    then first pointer is
iterates to next character and second pointer comes to previous and then they are again compared. If at
any point the characters for the 2 pointers are not equal then return false ,else the process is continued
till the start pointer exceeds the end pointer i.e. all elements have been compared. If all characters are
equal come out of loop and return true.

flowchart-

code-

#include <bits/
stdc+ +.h>
using na mespace s
td;

 bool su bset(stri
ng a, st ring b) {
      if (a == b)
      re turn true
;

      in t j = 0;
      for(int i = 0; i < b.size(); i++){
         if(a[j] == b[i])
         {j++;}
         if(j == a.size())
        {

        return true;}
      }
      return false;
   }

int length(string s)
{
    int cnt=0;
    for(int i=0;s[i]!='\0';i++)
    {

        cnt++;
    }

     return cnt;
}
   void compare(string a,string b)
   {
    int i=0;
       if(length(a)==length(b))
       {
           if(a==b)
           {

               cout<<"equal";
               return;
           }
           while(a[i]!='\0')
           {
               if(a[i]>b[i])
               {
                   cout<<"a>b";
                   return;
               }
               else if(a[i]<b[i])
               {
                   cout<<"b>a";
                   return;
               }
               else if(a[i]==b[i])
               {
                   i++;
               }
           }

       }
       else if(length(a)!=length(b)){
        int i=0;
        int j=0;
        while(a[i]!='\0'&&b[j]!='\0')
        {
            if(a[i]>b[j])
            {
                cout<<"a>b";
                break;
                return;

            }
            else if(a[i]<b[j]){
                    cout<<"b>a";
                    break;
                    return;

            }
            else if(a[i]==b[j])
            {
                i++;
                j++;

            }

        }
        if(subset(b,a)||subset(a,b))
        {if(length(a)>length(b))
        {
            cout<<"a>b";
        }
        else{
            cout<<"b>a";
        }}
       }

   }
bool palindrome(string s)
{

bool flag;
int i=0;
int j=length(s)-1;

    while(i<j){
        if(s[i]==s[j])
        {
            flag=true;
        }
        else
        {
             flag=false;
        }
        i++;
        j--;}

   return flag;
}
string concatenate(string &a,string &b)
{
    string s;

    for(int i=0;i<length(a);i++)
    {
        s.push_back(a[i]);

    }
    for(int i=0;i<length(b);i++)
    {

        s.push_back(b[i]);
    }
    return s;

}
int main()
{
    string s;
    cin>>s;
    cout<<length(s);
    if(palindrome(s))
    {
        cout<<"yes palindrome";
   }
   else{
        cout<<"not palindrome";
    }
    string a;
    cin>>a;
    if(subset(s,a))
    {
        if s is a subset of a
        cout<<"yes subset"<<endl;
    }
    else{
        cout<<"not subset"<<endl;
   }

    //cout<<length(s);
    string b;
    cin>>b;
    cout<<concatenate(s,b);
    compare(s,b);

    return 0;

output for different input-

conclusion-

We learnt how to use 2 pointer approach in strings and also to use bool type functions. We also learnt
the concept of palindromes and checked if a string is palindrome.
aim-to find if a string is a subset of another string

input-

input string 1

input string 2

output-

if string 1 is a subset of string 2 print yes subset otherwise print not subset.

algorithm-

Take 2 pointers pointing to start of smaller and bigger string respectively. Now, the iterator pointing to
bigger string is updated to next for each string and the iterator for small iterator is updated to next only
if they point to same character and if the iterator for small string points to end of smaller string then its a
subset otherwise the loop for bigger string's iterator also ends without finding common elements and
hence come out of the loop and return false.
flowchart-
code-

#include<bits/stdc++.h>
using namespace std;

 bool subset(string a, string b) {
      if(a == b)
      return true;

      int j = 0;
      for(int i = 0; i < b.size(); i++){
         if(a[j] == b[i])
         {j++;}
         if(j == a.size())
        {

        return true;}
      }
      return false;
   }

int length(string s)
{
    int cnt=0;
    for(int i=0;s[i]!='\0';i++)
    {

        cnt++;
    }

     return cnt;
}
   void compare(string a,string b)
   {
    int i=0;
       if(length(a)==length(b))
       {
           if(a==b)
           {

               cout<<"equal";
               return;
           }
           while(a[i]!='\0')
           {
               if(a[i]>b[i])
               {
                   cout<<"a>b";
                   return;
               }
               else if(a[i]<b[i])
               {
                   cout<<"b>a";
                   return;
               }
               else if(a[i]==b[i])
               {
                   i++;
               }
           }

       }
       else if(length(a)!=length(b)){
        int i=0;
        int j=0;
        while(a[i]!='\0'&&b[j]!='\0')
        {
            if(a[i]>b[j])
            {
                cout<<"a>b";
                break;
                return;

            }
            else if(a[i]<b[j]){
                    cout<<"b>a";
                    break;
                    return;

            }
            else if(a[i]==b[j])
            {
                i++;
                j++;

            }

        }
        if(subset(b,a)||subset(a,b))
        {if(length(a)>length(b))
        {
            cout<<"a>b";
        }
        else{
            cout<<"b>a";
        }}

       }

   }
bool palindrome(string s)
{

bool flag;
int i=0;
int j=length(s)-1;

    while(i<j){
        if(s[i]==s[j])
        {
            flag=true;
        }
        else
        {
             flag=false;
        }
        i++;
        j--;}

   return flag;
}
string concatenate(string &a,string &b)
{
    string s;

    for(int i=0;i<length(a);i++)
    {
        s.push_back(a[i]);

    }
    for(int i=0;i<length(b);i++)
    {

        s.push_back(b[i]);
    }
    return s;
}

int main()
{
    string s;
    cin>>s;
    cout<<length(s);
    if(palindrome(s))
    {
        cout<<"yes palindrome";
   }
   else{
        cout<<"not palindrome";
    }
    string a;
    cin>>a;
    if(subset(s,a))
    {
        if s is a subset of a
        cout<<"yes subset"<<endl;
    }
    else{
        cout<<"not subset"<<endl;
   }

    //cout<<length(s);
    string b;
    cin>>b;
    cout<<concatenate(s,b);
    compare(s,b);

    return 0;

}
outputs for diff inputs
conclusion-

We again used two pointer approach to check whether a string is palindrome or not.

Learning-

We learnt the concept of subset and hence checked if a string is subset of another string.

4.

aim-To compare 2 strings.

input-

input string 1

input string 2

output-

a>b if a is larger

b>a if b is larger

equal if both equal

algorithm-
first if length of 2 string is equal check whose character comes first in dictionary and that is larger, if both
strings are equal print equal. If lengths are not equal check whose character comes first in dictionary and
that is larger. Now, check if one string is a subset of another string then the string which is longer is
larger.
flowchart-
code-

#include<bits/stdc++.h>
using namespace std;

 bool subset(string a, string b) {
      if(a == b)
      return true;

      int j = 0;
      for(int i = 0; i < b.size(); i++){
         if(a[j] == b[i])
         {j++;}
         if(j == a.size())
        {

        return true;}
      }
      return false;
   }

int length(string s)
{
    int cnt=0;
    for(int i=0;s[i]!='\0';i++)
    {

        cnt++;
    }

     return cnt;
}
   void compare(string a,string b)
   {
    int i=0;
       if(length(a)==length(b))
       {
           if(a==b)
           {

               cout<<"equal";
               return;
           }
           while(a[i]!='\0')
           {
               if(a[i]>b[i])
               {
                   cout<<"a>b";
                   return;
               }
               else if(a[i]<b[i])
               {
                   cout<<"b>a";
                   return;
               }
               else if(a[i]==b[i])
               {
                   i++;
               }
           }

       }
       else if(length(a)!=length(b)){
        int i=0;
        int j=0;
        while(a[i]!='\0'&&b[j]!='\0')
        {
            if(a[i]>b[j])
            {
                cout<<"a>b";
                break;
                return;

            }
            else if(a[i]<b[j]){
                    cout<<"b>a";
                    break;
                    return;

            }
            else if(a[i]==b[j])
            {
                i++;
                j++;

            }

        }
        if(subset(b,a)||subset(a,b))
        {if(length(a)>length(b))
        {
            cout<<"a>b";
        }
        else{
            cout<<"b>a";
        }}

       }

   }
bool palindrome(string s)
{

bool flag;
int i=0;
int j=length(s)-1;

    while(i<j){
        if(s[i]==s[j])
        {
            flag=true;
        }
        else
        {
             flag=false;
        }
        i++;
        j--;}

   return flag;
}
string concatenate(string &a,string &b)
{
    string s;

    for(int i=0;i<length(a);i++)
    {
        s.push_back(a[i]);

    }
    for(int i=0;i<length(b);i++)
    {

        s.push_back(b[i]);
    }
    return s;

int main()
{
    string s;
    cin>>s;
    cout<<length(s);
    if(palindrome(s))
    {
        cout<<"yes palindrome";
   }
   else{
        cout<<"not palindrome";
    }
    string a;
    cin>>a;
    if(subset(s,a))
    {
        if s is a subset of a
        cout<<"yes subset"<<endl;
    }
    else{
        cout<<"not subset"<<endl;
   }

    //cout<<length(s);
    string b;
    cin>>b;
    cout<<concatenate(s,b);
    compare(s,b);

    return 0;

}
output for different inputs-

conclusion-

We compared two strings using c++ without using inbuilt strcmp function in c++ libraries.

Learning-

We learnt how to compare two strings by first comparing their length and then comparing their each
element.
EXPERIMENT 2- SEARCHES IN AN ARRAY
2.1.

Aim-Linear search in an array.

INPUT

input no of elements in array

input the target key

input the elements of array

Output

index at which target is present

Algorithm

Iterate over each element of array. If any one element is equal to the key, print the index of that. Else
print not found.

Flowchart-

Code-

#include<bi ts/stdc++.h>
using names pace std;
int main()
{

    int n,k ey;
    cin>>n> >key;
    int a[1 00];
    for(in t i=0;i<n;i+
+)
    {

        cin >>a[i];
    }
int flag=0;
    for(in t i=0;i<n;i+
+)
    {

        if(a[i]==key)
        {

            cout<<i<<endl;
flag=1;
            break;
        }
    }
if(flag==0){
cout<<"not found"<<endl;}

return 0;}

Output for different inputs-

Conclusion-

We learnt to use for loop to iterate over an array and found index at which target is present. We also saw
that it iterates over array.

Learning-

We have learnt how to access all the elements of an array.

2.2.

Aim-to do binary search in an array


Input-

Input no of elements in an array

Input elements of the array in ascending order

input the target key

Output-

Index at which element is present

Algorithm-we divide array in 2 parts Then search for the element in smaller parts. We keep on dividing
into smaller parts till we reach single elements and there if our key to search matches we return the
position.
Flowchart-

Code-

#include<bits/stdc++.h>
using namespace std;
int binarysearch(int s,int e,int v[1000],int key)
{
    if(s>e)
    {
        cout<<"element not found ";
        return -1;
    }
    int mid=(s+e)/2;
    if(v[mid]==key)
    {
        return mid;
    }
   else if(key>v[mid])
   {
       return binarysearch(mid+1,e,v,key);
   }
   else if(key<v[mid])
   {
       return binarysearch(s,mid-1,v,key);
   }

}
int main()
{
    vector<int>v;
    cout<<"no of elements"<<endl;
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        int inp;
        cin>>inp;
        v.push_back(inp);
    }
    int arr[1000];

    for(int i=0;i<n;i++)
    {
        cout<<v[i];
    }
    sort(v.begin(),v.end());
    for(int i=0;i<n;i++)
    {
        arr[i]=v[i];
    }

    int key;
    cin>>key;
    cout<<binarysearch(0,n-1,arr,key);
    return 0;
}
Output for different inputs-

Conclusion-

We understood algo of binary search to understand how to search for key in array.

Learning-

We learnt how to access an intermediate element of an array and how to divide the array in sub parts.

EXPERIMENT 3- SORTING ALGORITHMS


1. Selection Sort
2. Insertion Sort
3. Bubble Sort
4. Merge Sort
5. Quick Sort
Selection Sort
Aim: To sort a given array containing integers in ascending order
Input: We make an array containing integer numbers and then insert integers in that array in
any order.
Output: Output will be Sorted array
Algorithm:
    The selection sort algorithm sorts an array by repeatedly finding the minimum
element (considering ascending order) from unsorted part and putting it at the beginning. The
algorithm maintains two subarrays in a given array.

1) The subarray which is already sorted. 


2) Remaining subarray which is unsorted.

In every iteration of selection sort, the minimum element (considering ascending order) from
the unsorted subarray is picked and moved to the sorted subarray. 

Flowchart:
Code:
#include<bits/stdc++.h>
using namespace std;

void selectionSort(int arr[], int n){
    
    for(int i = 0; i < n; i++){
        int min_ind = i;
        
        for(int j = i + 1; j < n; j++){
            if(arr[j] < arr[min_ind]){
                min_ind = j;
            }
        }
        
        swap(arr[i], arr[min_ind]);
    }
    
    
}

int main() {
    int capacity;
    cout<<"Enter the capacity of array to be sorted"<<endl;
    cin>>capacity;
    int a[capacity];
    cout<<"Add elements to array"<<endl;
    for(int i=0; i<capacity; i++)
    {
        cin>>a[i];
    }
    selectionSort(a, capacity);
    for(int i = 0;i < capacity; i++){
        cout<<a[i]<<" ";
    }
    return 0;
}

Output:
Insertion Sort
Aim: To sort a given array containing integers in ascending order
Input: We make an array containing integer numbers and then insert integers in that array in
any order.
Output: Output will be Sorted array

Algorithm:
1.The first element in the array is assumed to be sorted. Take the second element and store it
separately in key. Compare key with the first element. If the first element is greater than key,
then key is placed in front of the first element.
2. Now, the first two elements are sorted. Take the third element and compare it with the
elements on the left of it. Placed it just behind the element smaller than it. If there is no
element smaller than it, then place it at the beginning of the array.
3. Similarly, place every unsorted element at its correct position.

Flowchart:
Code:
#include<bits/stdc++.h>
using namespace std;

void iSort(int arr[],int n){
    
    for(int i=1;i<n;i++){
        int key = arr[i];
        int j=i-1;
        while(j>=0 && arr[j]>key){
            arr[j+1]=arr[j];
            j--;
        }
        arr[j+1]=key;
    }
}

int main() {
    
    int capacity;
    cout<<"Enter the capacity of array to be sorted"<<endl;
    cin>>capacity;
    int a[capacity];
    cout<<"Add elements to array"<<endl;
    for(int i=0; i<capacity; i++)
    {
        cin>>a[i];
    }
    iSort(a,capacity);
    
    for(auto x: a)
        cout<<x<<" ";
}

Output:
Bubble Sort
Aim: To sort a given array containing integers in ascending order
Input: We make an array containing integer numbers and then insert integers in that array in
any order.
Output: Output will be Sorted array.
Algorithm:
1. Starting with the first element (index = 0), compare the current element with the next
element of the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next element, move to the next element. Repeat
Step 1.

Flowchart:
Code:
#include<bits/stdc++.h>
using namespace std;

void bubbleSort(int arr[], int n){
    
    bool swapped;
    for(int i = 0;i < n; i++){
        
        swapped = false;
        for(int j = 0 ; j < n - i -1; j++){
            if( arr[j] > arr[j+1]){
                swap(arr[j], arr[j+1]);
                swapped = true;
            }
        }
        
        if( swapped == false)
        break;
    }
}

int main() {
    int capacity;
    cout<<"Enter the capacity of array to be sorted"<<endl;
    cin>>capacity;
    int a[capacity];
    cout<<"Add elements to array"<<endl;
    for(int i=0; i<capacity; i++)
    {
        cin>>a[i];
    }
    bubbleSort(a, capacity);
    for(int i = 0; i < capacity; i++){
        cout<<a[i]<<" ";
    }
    return 0;
}

Output
Merge Sort
Aim: To sort a given array containing integers in ascending order
Input: We make an array containing integer numbers and then insert integers in that array in
any order.
Output: Output will be Sorted array
Algorithm:
1. It works by recursively dividing an array into two equal halves, sorting and then merging
each sorted half.
2. Merge sort is example of a divide and conquer algorithm. Broadly speaking, a divide and
conquer algorithm has the following parts:
Divide: This involves dividing the problem into subproblems
Conquer: recursively process sub problems until each one is solved
Combine: combine solved sub problems to give a solution to the original problem

Flowchart:
Code:
#include <iostream>
#include <algorithm>
using namespace std;

void merge(int arr[], int l, int m, int h)
{

    int n1 = m - l + 1, n2 = h - m;

    int left[n1], right[n2];

    for (int i = 0; i < n1; i++)
        left[i] = arr[i + l];

    for (int j = 0; j < n2; j++)
        right[j] = arr[m + 1 + j];
    int i = 0, j = 0, k = l;
    while (i < n1 && j < n2)
    {
        if (left[i] <= right[j])
            arr[k++] = left[i++];
        else
            arr[k++] = right[j++];
    }

    while (i < n1)
        arr[k++] = left[i++];
        
    while (j < n2)
        arr[k++] = right[j++];
}

void mergeSort(int arr[], int l, int r)
{
    if (r > l)
    {
        int m = l + (r - l) / 2;
        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);
        merge(arr, l, m, r);
    }
}

int main()
{
    int capacity;
    cout<<"Enter the capacity of array to be sorted"<<endl;
    cin>>capacity;
    int a[capacity];
    cout<<"Add elements to array"<<endl;
    for(int i=0; i<capacity; i++)
    {
        cin>>a[i];
    }
    int l = 0, r = capacity-1;

    mergeSort(a, l, r);
    for (int x : a)
        cout << x << " ";
}
Output:
Quick Sort
Aim: To sort a given array containing integers in ascending order
Input: We make an array containing integer numbers and then insert integers in that array in
any order.
Output: Output will be Sorted array
Algorithm: Quicksort is a sorting algorithm based on the divide and conquer approach where:
1. An array is divided into subarrays by selecting a pivot element (element selected from the array).
While dividing the array, the pivot element should be positioned in such a way that elements
less than pivot are kept on the left side and elements greater than pivot are on the right side of
the pivot.
2. The left and right subarrays are also divided using the same approach. This process continues
until each subarray contains a single element.
3. At this point, elements are already sorted. Finally, elements are combined to form a sorted array

Flowchart:
Code:
#include <bits/stdc++.h>
using namespace std;

int partition(int arr[], int l, int h)
{
    int pivot = arr[l];
    int i = l - 1, j = h + 1;
    while (true)
    {
        do
        {
            i++;
        } while (arr[i] < pivot);
        do
        {
            j--;
        } while (arr[j] > pivot);
        if (i >= j)
            return j;
        swap(arr[i], arr[j]);
    }
}

void qSort(int arr[], int l, int h)
{
    if (l < h)
    {
        int p = partition(arr, l, h);
        qSort(arr, l, p);
        qSort(arr, p + 1, h);
    }
}

int main()
{

    int capacity;
    cout<<"Enter the capacity of array to be sorted"<<endl;
    cin>>capacity;
    int a[capacity];
    cout<<"Add elements to array"<<endl;
    for(int i=0; i<capacity; i++)
    {
        cin>>a[i];
    }

    qSort(a, 0, capacity - 1);

    for (int x : a)
        cout << x << " ";
}
Output:
EXPERIMENT 4- STACKS
Aim: To make a stack data structure and implement push, pop functions in it.

Input: Elements to be inserted in stack

Output: Elements present in stack or uppermost element in stack.

Algorithm:
1. Making a structure named myStack.
2. Dynamically allocating space for array using a constructor.
3. Initialize the pointer position for array and capacity of array.
4. Making push function for inserting an element x, which moves the pointer 1 position
ahead and then put user provided element in that array.
5. Making pop function which just remove topmost element from the stack. And returns its
value.
Code:
#include<bits/stdc++.h>
using namespace std;

struct myStack
{
    int *arr;
    int top;
    int cap;
    myStack(int c)
    {
        cap = c;
        top = -1;
        arr = new int[cap];
    }

    void push( int x)
    {
        if(top==cap-1)
        {
            cout<<"overflow"<<endl;
        }
        else
        {
            top++;
            arr[top] = x;
        }
    }
    int pop()
    {
        if(top==(-1))
        {
            cout<<"Underflow"<<endl;
            return INT_MAX;

        }
        else
        {
            int res = arr[top];
            top--;
            return res;
        }
    }
    int peek()
    {
        return arr[top];
    }

};

int main()
{
    myStack s(5);

    for(int i=0 ; i<5 ; i++)
    {
        cout<<"enter element to the stack"<<endl;
        int n;
        cin>>n;
        s.push(n);
    }

    cout<<"Stack is : ";
    for(int i=0 ; i<5 ; i++)
    {
        
        cout<<s.peek()<<" ";
        s.pop();
    }
}
Output:

EXPERIMENT 5- INFIX TO POSTFIX CONVERSION


1. Infix to Postfix Conversion
2. Infix to Prefix Conversion.

Infix To Postfix
Aim: To convert expressions like a+b(infix) to ab+(postfix).
Input: An infix expression in the form of string.
Output: A resultant Postfix expression conversion of user provided infix expression.
Algorithm:
Code:
#include<iostream>
#include<stack>
#include<string>

using namespace std;

//INFIX TO POSTFIX CONVERSION

int helper(char c)
{
    if(c == '^')
      return 3;
    else if(c == '*' || c == '/')
      return 2;
    else if(c == '+' || c == '-')
      return 1;
    else
      return 0;
}

string InfixToPostfix(string infix)
{
    stack<char> s;
    string postfix;
    for(int i=0; i< infix.length(); i++)
    {
        if((infix[i] >= 'a' && infix[i] <= 'z') || (infix[i] >= 'A' && infix[i] 
<= 'Z')){
            postfix+=infix[i];
        }
        else if(infix[i] == '('){
            s.push(infix[i]);
        }
        else if(infix[i] == ')'){
            while((s.top()!='(') && (!s.empty())){
                postfix+=s.top();
                s.pop();
            }
            if(s.top()=='('){
                s.pop();
            }
        }
        else{
            if(s.empty()){
                s.push(infix[i]);
            }
            else
            {
                if(helper(infix[i])>helper(s.top())){
                    s.push(infix[i]);
                }
                else if((helper(infix[i])== helper(s.top())) && (infix[i]=='^'))
{
                    s.push(infix[i]);
                }
                else
                {
                    while((!s.empty())&&( helper(infix[i])<=helper(s.top()))){
                        postfix+=s.top();
                        s.pop();
                    }
                    s.push(infix[i]);
                }
            }
        }
    }
    while(!s.empty())
    {
        postfix+=s.top();
        s.pop();
    }

    return postfix;
}

int main()
{

    string infix, res;
    cin>>infix;
    res= InfixToPostfix(infix);
    cout<<res;
    return 0;
}

Conclusion: We can change infix to postfix that helps computer to operate faster.
Infix To Prefix

Aim: To convert expressions like a+b(infix) to +ab(prefix).


Input: An infix expression in the form of string.
Output: A resultant Prefix expression conversion of user provided infix expression.
Algorithm:
Code:
#include <iostream>
#include <stack>
#include <string>
#include <algorithm>

using namespace std;

//INFIX TO PREFIX CONVERSION

int helper(char c)
{
    if (c == '^')
        return 3;
    else if (c == '*' || c == '/')
        return 2;
    else if (c == '+' || c == '-')
        return 1;
    else
        return 0;
}

string InfixToPrefix(string infix)
{
    stack<char> s;
    string prefix;
    reverse(infix.begin(), infix.end());

    for (int i = 0; i < infix.length(); i++)
    {
        if (infix[i] == '(')
        {
            infix[i] = ')';
        }
        else if (infix[i] == ')')
        {
            infix[i] = '(';
        }
    }
    for (int i = 0; i < infix.length(); i++)
    {
        if ((infix[i] >= 'a' && infix[i] <= 'z') || (infix[i] >= 'A' && infix[i] 
<= 'Z'))
        {
            prefix += infix[i];
        }
        else if (infix[i] == '(')
        {
            s.push(infix[i]);
        }
        else if (infix[i] == ')')
        {
            while ((s.top() != '(') && (!s.empty()))
            {
                prefix += s.top();
                s.pop();
            }

            if (s.top() == '(')
            {
                s.pop();
            }
        }
        else
        {
            if (s.empty())
            {
                s.push(infix[i]);
            }
            else
            {
                if (helper(infix[i]) > helper(s.top()))
                {
                    s.push(infix[i]);
                }
                else if ((helper(infix[i]) == helper(s.top())) && (infix[i] == '
^'))
                {
                    while ((helper(infix[i]) == helper(s.top())) && (infix[i] == 
'^'))
                    {
                        prefix += s.top();
                        s.pop();
                    }
                    s.push(infix[i]);
                }
                else if (helper(infix[i]) == helper(s.top()))
                {
                    s.push(infix[i]);
                }
                else
                {
                    while ((!s.empty()) && (helper(infix[i]) < helper(s.top())))
                    {
                        prefix += s.top();
                        s.pop();
                    }
                    s.push(infix[i]);
                }
            }
        }
    }

    while (!s.empty())
    {
        prefix += s.top();
        s.pop();
    }

    reverse(prefix.begin(), prefix.end());
    return prefix;
}

int main()
{

    string infix, res;
    cin >> infix;
    res = InfixToPrefix(infix);
    cout << res;
    return 0;
}

Conclusion: We can change infix to prefix that helps computer to operate faster.
EXPERIMENT 6- BALANCED PARENTHESIS USING STACKS

Aim: To check if given string has all parenthesis balanced or not.


Input: An expression in the form of string, that only contains parenthesis (, {, [,],},).
Output: A Boolean expression that return yes for balanced parenthesis and no otherwise.
Algorithm:
Code:
#include <bits/stdc++.h>
using namespace std;

bool areBracketsBalanced(string str)
{
    stack<char> s;

    char x;

    for (int i = 0; i < str.length(); i++)
    {
        if (str[i] == '(' || str[i] == '[' || str[i] == '{')
        {
            s.push(str[i]);
            continue;
        }

        if (s.empty())
            return false;

        switch (str[i])
        {
        case ')':

            x = s.top();
            s.pop();
            if (x == '{' || x == '[')
                return false;
            break;

        case '}':
            x = s.top();
            s.pop();
            if (x == '(' || x == '[')
                return false;
            break;

        case ']':

            x = s.top();
            s.pop();
            if (x == '(' || x == '{')
                return false;
            break;
        }
    }

    return (s.empty());
}

int main()
{
    string str;
    cin >> str;

    if (areBracketsBalanced(str))
        cout << "Balanced";
    else
        cout << "Not  Balanced";
    return 0;
}

Conclusion: We can check for parenthesis in any given string using the above code.
EXPERIMENT 7- QUEUE OPERATIONS
7.1.

Aim- To implement queue using Linked List

Input- Some numbers to be stored in queues using linked list

Code-
#include <bits/stdc++.h>
using namespace std;

struct QNode
{
    int data;
    QNode *next;
    QNode(int d)
    {
        data = d;
        next = NULL;
    }
};

struct Queue
{
    QNode *front, *rear;
    Queue()
    {
        front = rear = NULL;
    }

    void enQueue(int x)
    {

        QNode *temp = new QNode(x);

        if (rear == NULL)
        {
            front = rear = temp;
            return;
        }
        rear->next = temp;
        rear = temp;
    }

    void deQueue()
    {
        if (front == NULL)
            return;

        QNode *temp = front;
        front = front->next;

        if (front == NULL)
            rear = NULL;

        delete (temp);
    }
};

int main()
{

    Queue q;
    q.enQueue(100);
    q.enQueue(200);
    q.deQueue();
    q.deQueue();
    q.enQueue(130);
    q.enQueue(400);
    q.enQueue(5);
    q.deQueue();
    cout << "Queue Front : " << (q.front)->data << endl;
    cout << "Queue Rear : " << (q.rear)->data;
}

Output-

Conclusion- We have stored integers using queue implemented through linked list.

Learning- We have learnt how to implement queue using stacks and retrieve first and last
element of queue.

7.2.

Aim- To implement queue using stack

Input- Some numbers to be stored in stack and then in queue

Code-
#include <bits/stdc++.h>

using namespace std;

class Stack
{
    queue<int> q1, q2;

    int curr_size;

public:
    Stack()
    {
        curr_size = 0;
    }

    void push(int x)
    {
        curr_size++;

        q2.push(x);

        while (!q1.empty())
        {
            q2.push(q1.front());
            q1.pop();
        }

        // swap the names of two queues
        queue<int> q = q1;
        q1 = q2;
        q2 = q;
    }

    void pop()
    {

        // if no elements are there in q1
        if (q1.empty())
            return;
        q1.pop();
        curr_size--;
    }

    int top()
    {
        if (q1.empty())
            return -1;
        return q1.front();
    }

    int size()
    {
        return curr_size;
    }
};

int main()
{
    Stack s;
    s.push(6);
    s.push(14);
    s.push(30);
    s.push(46);
    s.push(25);

    cout << "current size: " << s.size()
         << endl;
    cout << s.top() << endl;
    s.pop();
    cout << s.top() << endl;
    s.pop();
    cout << s.top() << endl;

    cout << "current size: " << s.size()
         << endl;
    return 0;
}

Output-

Conclusion- We have implemented queues using stacks and enqueued and dequeued
elements.

Learning- We have learnt how to implement queues using stacks and how to store elements in
a queue.

7.3.

Aim- To construct a circular queue.

Input- Giving numbers for a queue and performing queue operations in queue.

Code-
#include <bits/stdc++.h>
using namespace std;

class Queue
{
    // Initialize front and rear
    int rear, front;

    // Circular Queue
    int size;
    int *arr;
public:
    Queue(int s)
    {
        front = rear = -1;
        size = s;
        arr = new int[s];
    }

    void enQueue(int value);
    int deQueue();
    void displayQueue();
};

/* Function to create Circular queue */
void Queue::enQueue(int value)
{
    if ((front == 0 && rear == size - 1) ||
        (rear == (front - 1) % (size - 1)))
    {
        printf("\nQueue is Full");
        return;
    }

    else if (front == -1) /* Insert First Element */
    {
        front = rear = 0;
        arr[rear] = value;
    }

    else if (rear == size - 1 && front != 0)
    {
        rear = 0;
        arr[rear] = value;
    }

    else
    {
        rear++;
        arr[rear] = value;
    }
}

// Function to delete element from Circular Queue
int Queue::deQueue()
{
    if (front == -1)
    {
        printf("\nQueue is Empty");
        return INT_MIN;
    }

    int data = arr[front];
    arr[front] = -1;
    if (front == rear)
    {
        front = -1;
        rear = -1;
    }
    else if (front == size - 1)
        front = 0;
    else
        front++;

    return data;
}

// Function displaying the elements
// of Circular Queue
void Queue::displayQueue()
{
    if (front == -1)
    {
        printf("\nQueue is Empty");
        return;
    }
    printf("\nElements in Circular Queue are: ");
    if (rear >= front)
    {
        for (int i = front; i <= rear; i++)
            printf("%d ", arr[i]);
    }
    else
    {
        for (int i = front; i < size; i++)
            printf("%d ", arr[i]);

        for (int i = 0; i <= rear; i++)
            printf("%d ", arr[i]);
    }
}

/* Driver of the program */
int main()
{
    Queue q(5);

    // Inserting elements in Circular Queue
    q.enQueue(23);
    q.enQueue(12);
    q.enQueue(123);
    q.enQueue(-89);

    // Display elements present in Circular Queue
    q.displayQueue();

    // Deleting elements from Circular Queue
    printf("\nDeleted value = %d", q.deQueue());
    printf("\nDeleted value = %d", q.deQueue());

    q.displayQueue();

    q.enQueue(9);
    q.enQueue(21);
    q.enQueue(53);

    q.displayQueue();

    q.enQueue(20);
    return 0;
}

Output-

Conclusion- We have implemented circular queue and performed queue operations.


Learning- We have learned how to implement circular queue.

EXPERIMENT 8- TREE TRAVERSAL

8.1
AIM: Pre-Order tree traversal

INPUT: No input Required by user

CODE:
#include<bits/stdc++.h>
using namespace std;

struct Node
{
    int key;
    Node* left ;
    Node* right;
    Node(int x)
    {
        key =x;
        left = NULL;
        right = NULL;
    }
};

void preorder(Node* root)


{
    if(root==NULL)
        return;

    cout<< root->key<<" ";  


    preorder(root->left);
    preorder(root->right);  
}

int main()
{
    Node* root = new Node(10);
    root->left = new Node(20);
    root->right = new Node(30);
    root->left->left = new Node(100);
    root->left->right = new Node(200);
    root->right->right = new Node(50);

    preorder(root);

    return 0;
}    

OUTPUT:

CONCLUSION: We can print all nodes of tree recursively in a particular


manner(pre-order)

8.2
AIM: In-Order tree traversal

INPUT: No input Required by user

CODE:
#include<bits/stdc++.h>
using namespace std;

struct Node
{
    int key;
    Node* left ;
    Node* right;
    Node(int x)
    {
        key =x;
        left = NULL;
        right = NULL;
    }
};

void inorder(Node* root)


{
    if(root==NULL)
        return;

    inorder(root->left);
    cout<< root->key<<" ";
    inorder(root->right);    
}

int main()
{
    Node* root = new Node(10);
    root->left = new Node(20);
    root->right = new Node(30);
    root->left->left = new Node(100);
    root->left->right = new Node(200);
    root->right->right = new Node(50);

    inorder(root);

    return 0;
}

OUTPUT:

CONCLUSION: We can print all nodes of tree recursively in a particular manner(In-


order)

8.3
AIM: Post-Order tree traversal
INPUT: No input Required by user

CODE:
#include<bits/stdc++.h>
using namespace std;

struct Node
{
    int key;
    Node* left ;
    Node* right;
    Node(int x)
    {
        key =x;
        left = NULL;
        right = NULL;
    }
};

void postorder(Node* root)


{
    if(root==NULL)
        return;

    postorder(root->left);
    postorder(root->right);  
    cout<< root->key<<" ";  
}

int main()
{
    Node* root = new Node(10);
    root->left = new Node(20);
    root->right = new Node(30);
    root->left->left = new Node(100);
    root->left->right = new Node(200);
    root->right->right = new Node(50);

    postorder(root);

    return 0;
}
OUTPUT:

CONCLUSION: We can print all nodes of tree recursively in a particular


manner(post-order)
EXPERIMENT 9- TREE OPERATIONS
9.1

AIM: Insertion in Binary Tree

INPUT: We need to input an integer that will be key for inserted Node

CODE:
#include <bits/stdc++.h>

using namespace std;

struct Node
{
    int key;
    struct Node *left;
    struct Node *right;
    Node(int k)
    {
        key = k;
        left = right = NULL;
    }
};

Node *insert(Node *root, int x)


{
    Node *temp = new Node(x);
    Node *parent = NULL, *curr = root;
    while (curr != NULL)
    {
        parent = curr;
        if (curr->key > x)
            curr = curr->left;
        else if (curr->key < x)
            curr = curr->right;
        else
            return root;
    }
    if (parent == NULL)
        return temp;
    if (parent->key > x)
        parent->left = temp;
    else
        parent->right = temp;
    return root;
}

void inorder(Node *root)


{
    if (root != NULL)
    {
        inorder(root->left);
        cout << root->key << " ";
        inorder(root->right);
    }
}
int main()
{

    Node *root = new Node(10);


    root->left = new Node(5);
    root->right = new Node(15);
    root->right->left = new Node(12);
    root->right->right = new Node(18);
    int x;

    cout << "Enter an integer value for Node To be Inserted" << endl;
    cin >> x;

    root = insert(root, x);


    inorder(root);
}

OUTPUT:

CONCLUSION: We can iteratively insert Node to a Binary Tree


9.2

AIM: Deletion in Binary Tree

INPUT: The user should give key of pre-existing Node( Here done in main() )

CODE:
#include <bits/stdc++.h>
using namespace std;

struct Node  
{
  int key;
  struct Node *left;
  struct Node *right;
  Node(int k){
      key=k;
      left=right=NULL;
  }
};

Node *getSuccessor(Node *curr){


    curr=curr->right;
    while(curr!=NULL && curr->left!=NULL)
        curr=curr->left;
    return curr;
}

Node *delNode(Node *root, int x){


    if(root==NULL)
        return root;
    if(root->key>x)
        root->left=delNode(root->left,x);
    else if(root->key<x)
        root->right=delNode(root->right,x);
    else{
        if(root->left==NULL){
            Node *temp=root->right;
            delete root;
            return temp;
        }
        else if(root->right==NULL){
            Node *temp=root->left;
            delete root;
            return temp;
        }
        else{
            Node *succ=getSuccessor(root);
            root->key=succ->key;
            root->right=delNode(root->right,succ->key);
        }
    }
    return root;
}

void inorder(Node *root){


    if(root!=NULL){
        inorder(root->left);
        cout<<root->key<<" ";
        inorder(root->right);    
    }
}
int main() {
   
    Node *root=new Node(10);
    root->left=new Node(5);
    root->right=new Node(15);
    root->right->left=new Node(12);
    root->right->right=new Node(18);
    int x=15;
   
    root=delNode(root,x);
    inorder(root);
}

OUTPUT:

CONCLUSION: We recursively delete Node from tree after finding it


EXPERIMENT 10- BINARY TREE OPERATIONS
AIM: To make Binary Tree with 10 elements and perform

 If given node is leaf or not

 Deleting leaf node

 If given node is BST

 Count number of Nodes

INPUT: We need to input an root of tree made in main function.

CODE:
#include<bits/stdc++.h>
using namespace std;

struct Node
{
  int val;
  Node *left , *right;
  Node(int x)
  {
      val = x;
      left=NULL;
      right=NULL;
  }
};

void inorder(Node *root)/////////////////////////////// print


{
    if (root != NULL)
    {
        inorder(root->left);
        cout << root->val << " ";
        inorder(root->right);
    }
}

bool isPresent(Node* root , int x)  ///////////////////////////////


present  or not
{
    if(root == NULL)
        return false;

    if(root->val == x)
        return true;
    else if(root->val< x)
        return isPresent(root->right, x);
    else
        return isPresent(root->left, x);    

bool isLeaf(Node* root , int x)////////////////////////////////          


1
{
    if(isPresent(root,x)==false)
    {
        //cout<<"Given Element is not present in the tree"<<endl;
          return false;
    }
    else
    {
        if(root->val == x)
        {   if(root->right==NULL && root->left==NULL)
            {
                 //cout<<"GIVEN ELEMENT IS LEAF NODE"<<endl;
                   return true;
            }
            else
            {    
                //cout<<"GIVEN ELEMENT IS PRESENT IN TREE BUT NOT A LEAF
NODE!"<<endl;
                    return false ;
            }
        }          
        return (isLeaf(root->left, x)||isLeaf(root->right, x));
    }        
}

Node* deleteLeaf(Node* root , int x)///////////////////////////////      


2
{
    if(isLeaf(root,x)==false)
    {
        //cout<<"Given Is Not Leaf Node"<<endl;
        return root;
    }
    else
    {
        if(root== NULL) return NULL;
         root->left = deleteLeaf(root->left , x);
         root->right = deleteLeaf(root->right , x);

         if(root->val==x)
         {  
             return NULL;
         }
         return root;
    }
   
}
bool isBST(Node* root , int lo , int
hi)//////////////////////////////////////////////////////////////////////
//////////////////////////        3
{
    if(root==NULL) return true;

    if(!(root->val>lo && root->val<hi))


    {
        return false;
    }
    int x = root->val;
    return (isBST(root->left , lo , x) && isBST(root->right , x , hi));
   
}
int countNodes(Node* root )///////////////////////////////////////      
4
{
    if(root==NULL)
    {
       
        return 0 ;
    }
    return countNodes(root->left)+countNodes(root->right)+1;
}
int main()
{
    Node* root = new Node(100);//level 1                                
100
    root->left = new Node(50);// level                                  
50                     300
    root->right = new Node(300);//                                      
30         55          200      700
    root->left->left = new Node(30);// level 3                          
10     35    51   70
    root->left->right = new Node(55);//
    root->right->left = new Node(200);//
    root->right->right = new Node(7);//
    root->left->left->left = new Node(10);// level 4
    root->left->left->right = new Node(35);//
    root->left->right->left = new Node(51);//
    root->left->right->right = new Node(70);//

    inorder(root);
    cout<<"\n--------------------------------\n"<<endl;

    cout<<"Identifying if given Node is Leaf or not:\n";


    cout<<isLeaf(root,10)<<endl;
    cout<<isLeaf(root,100)<<endl;

     cout<<"\n--------------------------------\n"<<endl;

    cout<<"Deleting Node function: \n";


    Node* nroot = deleteLeaf(root,10);
    inorder(nroot);
   
     cout<<"\n--------------------------------\n"<<endl;

    cout<<"Identifying if given tree is BST or not:\n";


    bool res = isBST(root , INT_MIN , INT_MAX);
    cout<<res<<endl;
   
    cout<<"\n--------------------------------\n"<<endl;
   
    int value = countNodes(root);
    cout<<value<<endl;
   
   
    return 0;
}

OUTPUT:

CONCLUSION:

 We can find leaf if both children of Node are NULL and delete that
particular node.

 We can count Nodes of tree by traversing every node and on every non-
NULL node increasing counter.

 Tree is BST if it have only 2 children or less than 2 children. Left child smaller
than parent and right child greater than parent.
EXPERIMENT 11- BINARY TREE TRAVERSAL
AIM: TO TRAVERSE A BINARY TREE WITHOUT USING RECURSION (Level Order     
Traversal).

INPUT: We need to input the root of tree we want to print .

CODE:
#include<bits/stdc++.h>
using namespace std;

struct Node
{
  int val;
  Node *left , *right;
  Node(int x)
  {
      val = x;
      left=NULL;
      right=NULL;
  }
};

void inorder(Node *root)/////////////////////////////// print


{
    if (root != NULL)
    {
        inorder(root->left);
        cout << root->val << " ";
        inorder(root->right);
    }
}

void levelOrder(Node *root)/////////////////////////////// print


{
    Node* curr;
    queue<Node*> q;
    q.push(root);
    while(!q.empty())
    {
        curr=q.front();
        q.pop();
        if(curr->left)
            q.push(curr->left);
        if(curr->right)
            q.push(curr->right);
        cout<<curr->val << "  ";
    }
}

int main()
{
    Node* root = new Node(100);//level 1                                
100
    root->left = new Node(50);// level                                  
50                     300
    root->right = new Node(300);//                                      
30         55          200      700
    root->left->left = new Node(30);// level 3                          
10     35    51   70
    root->left->right = new Node(55);//
    root->right->left = new Node(200);//
    root->right->right = new Node(700);//
    root->left->left->left = new Node(10);// level 4
    root->left->left->right = new Node(35);//
    root->left->right->left = new Node(51);//
    root->left->right->right = new Node(70);//

    inorder(root);
    cout<<"\
n-------------------------------------------------------------\n";
    levelOrder(root);
   
   
    return 0;
}
OUTPUT:

CONCLUSION: We can print node data of tree either recursively or iteratively .


EXPERIMENT 13- BINARY TREE TRAVERSAL
AIM: To make a heap of 10 elements and perform insertion and deletion.

INPUT: Heaps are internally arrays hence we will have to pass array in each func.

CODE:
#include <bits/stdc++.h>
using namespace std;

void heapify(int arr[], int n, int i)


{
    int parent = (i - 1) / 2;
    if (arr[parent] > 0)
    {
        if (arr[i] > arr[parent])
        {
            swap(arr[i], arr[parent]);
            heapify(arr, n, parent);
        }
    }
}
void insertNode(int arr[], int &n, int Key)
{
    n = n + 1;
    arr[n - 1] = Key;
    heapify(arr, n, n - 1);
}
void deleteNode(int arr[], int &n)
{
    int lastElement = arr[n - 1];
    arr[0] = lastElement;
    n = n - 1;
    heapify(arr, n, 0);
}
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
    cout << "\n";
}
int main()
{
    int arr[100] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int n = 10;
    int a;
    cout << "Enter element to be inserted:";
    cin >> a;
    insertNode(arr, n, a);
    cout << "AFTER INSERTION:\n";
    printArray(arr, n);
    deleteNode(arr, n);
    cout << "\nAFTER DELETION:\n";
    printArray(arr, n);
    return 0;
}

OUTPUT:

CONCLUSION: We can print node data of tree either recursively or iteratively .


EXPERIMENT 13 – HEAP IMPLEMENTATION
AIM: To make a heap of 10 elements and perform insertion and deletion.

INPUT: Heaps are internally arrays hence we will have to pass array in each func.

CODE:
#include <bits/stdc++.h>
using namespace std;

void heapify(int arr[], int n, int i)


{
    int parent = (i - 1) / 2;
    if (arr[parent] > 0)
    {
        if (arr[i] > arr[parent])
        {
            swap(arr[i], arr[parent]);
            heapify(arr, n, parent);
        }
    }
}
void insertNode(int arr[], int &n, int Key)
{
    n = n + 1;
    arr[n - 1] = Key;
    heapify(arr, n, n - 1);
}
void deleteNode(int arr[], int &n)
{
    int lastElement = arr[n - 1];
    arr[0] = lastElement;
    n = n - 1;
    heapify(arr, n, 0);
}
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
    cout << "\n";
}
int main()
{
    int arr[100] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int n = 10;
    int a;
    cout << "Enter element to be inserted:";
    cin >> a;
    insertNode(arr, n, a);
    cout << "AFTER INSERTION:\n";
    printArray(arr, n);
    deleteNode(arr, n);
    cout << "\nAFTER DELETION:\n";
    printArray(arr, n);
    return 0;
}

OUTPUT:

CONCLUSION: We can implement heap using arrays and heapify is used to make
Binary Heap Balanced. And we implement insert and delete with the help of
heapify .
EXPERIMENT 14 – M-WAY SEARCH TREE
AIM: To implement multi-way Search tree and perform the following operations-

 Insertion

 Deletion

 Searching

 Traversal

INPUT: User have to choose between all operations i.e., Insertion, Deletion,
Searching and Traversal. Based on choice specific task takes place.

CODE:
#include <bits/stdc++.h>

using namespace std;

#define MAX 4
#define MIN 2

struct Node
{
    int val[MAX + 1], count;
    Node *link[MAX + 1];
};

Node *root;

/* creating new node */


Node *createNode(int val, Node *child)
{
    Node *newNode = new Node;
    newNode->val[1] = val;
    newNode->count = 1;
    newNode->link[0] = root;
    newNode->link[1] = child;
    return newNode;
}
/* Places the value in appropriate position */
void addValToNode(int val, int pos, Node *node, Node *child)
{
    int j = node->count;
    while (j > pos)
    {
        node->val[j + 1] = node->val[j];
        node->link[j + 1] = node->link[j];
        j--;
    }
    node->val[j + 1] = val;
    node->link[j + 1] = child;
    node->count++;
}

/* split the node */


void splitNode(int val, int *pval, int pos, Node *node, Node *child, Node
**newNode)
{
    int median, j;

    if (pos > MIN)


        median = MIN + 1;
    else
        median = MIN;

    *newNode = new Node;


    j = median + 1;
    while (j <= MAX)
    {
        (*newNode)->val[j - median] = node->val[j];
        (*newNode)->link[j - median] = node->link[j];
        j++;
    }
    node->count = median;
    (*newNode)->count = MAX - median;

    if (pos <= MIN)


    {
        addValToNode(val, pos, node, child);
    }
    else
    {
        addValToNode(val, pos - median, *newNode, child);
    }
    *pval = node->val[node->count];
    (*newNode)->link[0] = node->link[node->count];
    node->count--;
}

/* sets the value val in the node */


int setValueInNode(int val, int *pval, Node *node, Node **child)
{

    int pos;
    if (!node)
    {
        *pval = val;
        *child = NULL;
        return 1;
    }

    if (val < node->val[1])


    {
        pos = 0;
    }
    else
    {
        for (pos = node->count;
             (val < node->val[pos] && pos > 1); pos--)
            ;
        if (val == node->val[pos])
        {
            cout << "Duplicates not allowed\n";
            return 0;
        }
    }
    if (setValueInNode(val, pval, node->link[pos], child))
    {
        if (node->count < MAX)
        {
            addValToNode(*pval, pos, node, *child);
        }
        else
        {
            splitNode(*pval, pval, pos, node, *child, child);
            return 1;
        }
    }
    return 0;
}

/* insert val in B-Tree */


void insertion(int val)
{
    int flag, i;
    Node *child;

    flag = setValueInNode(val, &i, root, &child);


    if (flag)
        root = createNode(i, child);
}

/* copy successor for the value to be deleted */


void copySuccessor(Node *myNode, int pos)
{
    Node *dummy;
    dummy = myNode->link[pos];

    for (; dummy->link[0] != NULL;)


        dummy = dummy->link[0];
    myNode->val[pos] = dummy->val[1];
}

/* removes the value from the given node and rearrange values */
void removeVal(Node *myNode, int pos)
{
    int i = pos + 1;
    while (i <= myNode->count)
    {
        myNode->val[i - 1] = myNode->val[i];
        myNode->link[i - 1] = myNode->link[i];
        i++;
    }
    myNode->count--;
}

/* shifts value from parent to right child */


void doRightShift(Node *myNode, int pos)
{
    Node *x = myNode->link[pos];
    int j = x->count;

    while (j > 0)
    {
        x->val[j + 1] = x->val[j];
        x->link[j + 1] = x->link[j];
    }
    x->val[1] = myNode->val[pos];
    x->link[1] = x->link[0];
    x->count++;

    x = myNode->link[pos - 1];
    myNode->val[pos] = x->val[x->count];
    myNode->link[pos] = x->link[x->count];
    x->count--;
    return;
}

/* shifts value from parent to left child */


void doLeftShift(Node *myNode, int pos)
{
    int j = 1;
    Node *x = myNode->link[pos - 1];

    x->count++;
    x->val[x->count] = myNode->val[pos];
    x->link[x->count] = myNode->link[pos]->link[0];

    x = myNode->link[pos];
    myNode->val[pos] = x->val[1];
    x->link[0] = x->link[1];
    x->count--;

    while (j <= x->count)


    {
        x->val[j] = x->val[j + 1];
        x->link[j] = x->link[j + 1];
        j++;
    }
    return;
}
/* merge nodes */
void mergeNodes(Node *myNode, int pos)
{
    int j = 1;
    Node *x1 = myNode->link[pos], *x2 = myNode->link[pos - 1];

    x2->count++;
    x2->val[x2->count] = myNode->val[pos];
    x2->link[x2->count] = myNode->link[0];

    while (j <= x1->count)


    {
        x2->count++;
        x2->val[x2->count] = x1->val[j];
        x2->link[x2->count] = x1->link[j];
        j++;
    }

    j = pos;
    while (j < myNode->count)
    {
        myNode->val[j] = myNode->val[j + 1];
        myNode->link[j] = myNode->link[j + 1];
        j++;
    }
    myNode->count--;
    free(x1);
}

/* adjusts the given node */


void adjustNode(Node *myNode, int pos)
{
    if (!pos)
    {
        if (myNode->link[1]->count > MIN)
        {
            doLeftShift(myNode, 1);
        }
        else
        {
            mergeNodes(myNode, 1);
        }
    }
    else
    {
        if (myNode->count != pos)
        {
            if (myNode->link[pos - 1]->count > MIN)
            {
                doRightShift(myNode, pos);
            }
            else
            {
                if (myNode->link[pos + 1]->count > MIN)
                {
                    doLeftShift(myNode, pos + 1);
                }
                else
                {
                    mergeNodes(myNode, pos);
                }
            }
        }
        else
        {
            if (myNode->link[pos - 1]->count > MIN)
                doRightShift(myNode, pos);
            else
                mergeNodes(myNode, pos);
        }
    }
}

/* delete val from the node */


int delValFromNode(int val, Node *myNode)
{
    int pos, flag = 0;
    if (myNode)
    {
        if (val < myNode->val[1])
        {
            pos = 0;
            flag = 0;
        }
        else
        {
            for (pos = myNode->count;
                 (val < myNode->val[pos] && pos > 1); pos--)
                ;
            if (val == myNode->val[pos])
            {
                flag = 1;
            }
            else
            {
                flag = 0;
            }
        }
        if (flag)
        {
            if (myNode->link[pos - 1])
            {
                copySuccessor(myNode, pos);
                flag = delValFromNode(myNode->val[pos], myNode-
>link[pos]);
                if (flag == 0)
                {
                    cout << "Given data is not present in B-Tree\n";
                }
            }
            else
            {
                removeVal(myNode, pos);
            }
        }
        else
        {
            flag = delValFromNode(val, myNode->link[pos]);
        }
        if (myNode->link[pos])
        {
            if (myNode->link[pos]->count < MIN)
                adjustNode(myNode, pos);
        }
    }
    return flag;
}
/* delete val from B-tree */
void deletion(int val, Node *myNode)
{
    Node *tmp;
    if (!delValFromNode(val, myNode))
    {
        cout << "Given value is not present in B-Tree\n";
        return;
    }
    else
    {
        if (myNode->count == 0)
        {
            tmp = myNode;
            myNode = myNode->link[0];
            free(tmp);
        }
    }
    root = myNode;
    return;
}

/* search val in B-Tree */


void searching(int val, int *pos, Node *myNode)
{
    if (!myNode)
    {
        return;
    }

    if (val < myNode->val[1])


    {
        *pos = 0;
    }
    else
    {
        for (*pos = myNode->count;
             (val < myNode->val[*pos] && *pos > 1); (*pos)--)
            ;
        if (val == myNode->val[*pos])
        {
            cout << "Given data is Found\n";
            return;
        }
    }
    searching(val, pos, myNode->link[*pos]);
    return;
}

/* B-Tree Traversal */
void traversal(Node *myNode)
{
    int i;
    if (myNode)
    {
        for (i = 0; i < myNode->count; i++)
        {
            traversal(myNode->link[i]);
            cout << myNode->val[i + 1] << ' ';
        }
        traversal(myNode->link[i]);
    }
}

int main()
{
    int val, opt;
    while (true)
    {
        cout << "1. Insertion\t2. Deletion\n";
        cout << "3. Searching\t4. Traversal\n";
        cout << "5. Exit\nEnter your choice: ";
        cin >> opt;
        cout << endl;
        switch (opt)
        {
        case 1:
            cout << "Enter your input:";
            cin >> val;
            insertion(val);
            break;
        case 2:
            cout << "Enter the element to delete:";
            cin >> val;
            deletion(val, root);
            break;
        case 3:
            cout << "Enter the element to search:";
            cin >> val;
            searching(val, &opt, root);
            break;
        case 4:
            traversal(root);
            break;
        case 5:
            exit(0);
        }
        cout << endl;
    }

    return 0;
}
OUTPUT:

          Insertion output
Traversal output

      Deletion output
    Searching output

CONCLUSION: M-way search is an extension of Binary search tree and hence most
implementation is similar where search, traverse, delete functions are
implemented by recursion. It have wide applications.

You might also like