mardi 31 mai 2016

Balancing bracket algorithm (Recursion)-New Method

S, I have tried out my own new balancing algorithm using recursion.

The function parses through a string and when a new opening bracket is encountered,it calls itself using the latest encountered bracket as the new comparing bracket (hence fulfills the property of stack LIFO).Now if a closing bracket is encountered and it does not matches with the updated opening bracket,a false is returned and the program is terminated. If a closing matching bracket is encountered,a true is returned and function returns to its last calling instance.This continues till the length of string is parsed. A count function is also included to check the balance of pairs of brackets.

Below is my code.Please suggest me any improvements and bug fixes for making the algorithm better.Try focusing on the given structure and do not suggest alternate data structures such as stack,list,etc.

 int i=0,l=s.length(),count=0; //global variables
 // NULL is supplied in first call of s by calling object

 bool i(String c,char *s)
{
  char *t=s; // stores latest opening bracket encountered through recursion
  for(;i<l;i++) // l is length of string
 {
     if(c[i]=='{' || '(' || '[')
   {
      ++count;
      bool i(c,t);
   }

   else if(c[i]=='}' || ']' || ')')
   {
     if(c[i]==t <matching bracket for s>             
     {
       --count;
       return true;
     }   
     else 
     cout<<"sorry not balanced";
     exit(o); //terminate program after checking failure 
   }//else loop ends

   if(count==0)
   return true;
   else
   return false;
 } // string parsing ends
}    

Aucun commentaire:

Enregistrer un commentaire