Latest

6/recent/ticker-posts

How To Find The Next Nearest Letter Of A Character Present in a Sorted Character Array?

 PROBLEM STATEMENT:

You are given a sorted character array and character. We have to find the next nearest letter of the character that is found in the given array.

  For example for the array     {a  ,  d   , g  ,  k  ,  l  ,  m}, the next nearest letter of h is k and next nearest letter of l is m.

ALGORITHM:

1. Define a universal character variable temp to store the next character.

2. Find the middle character.

3.  If the middle character is greater than the given character, then store the middle character as temp and search for accurate result in the left part of the middle index.

4. If the middle character is equal to or less than the given character, search for the result in the right part of the middle index.

5. Repeat the result until only one element remain.

CODE:

#include <bits/stdc++.h>

using namespace std;

char temp='1';

int nextletter(char x,int l,int r,char a[])

{

    if(r>=l)

    {

    int middle=l+(r-l)/2;

    if(a[middle]<=x)

      return nextletter(x,middle+1,r,a);

    else if(a[middle]>x)

    {

        temp=a[middle];

        return nextletter(x,l,middle-1,a);

    }

    }

    return temp;      //if the element doesn't exist

}


int main()

{

    int n;  //size of array

    cin>>n;

    char a[n];

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

        cin>>a[i];

    char x;

    cin>>x;

    char ans=nextletter(x,0,n-1,a);

    cout<<ans;

    return 0;


}

INPUT

6

a    d    g    k    l    m

h

OUTPUT:

k




Post a Comment

0 Comments