Home > Enterprise >  binary search not returning the index
binary search not returning the index

Time:02-20

this is my c program for binary search and for some reason it is not returning the index of the element that I searched

#include <iostream>
//using  namespace std;

struct array {

    int A[10];
    int size;
    int length;
};


void displayArray(struct array arr) {
    std::cout << "the elements are :-" << std:: endl << '\t';
    for (int i = 0; i < arr.length; i  ) {

        std::cout << arr.A[i] << ',';
    }
    std::cout << std::endl;
    
}

int binarySearch(struct array arr, int element) {

    int l, h;
    l = 0;
    h = arr.length;

    for (int i = 0; l <= h; i  ) {
   
        int mid = (l   h) / 2;
        
        if (arr.A[mid] == element)
            return mid;
        else if (arr.A[mid] < element)
            h = mid -1;
        else
            l = mid 1;
        std::cout << mid << std::endl;
    }
    return -1;

}
int main()
{
    struct array arr = {{1,2,3,4,5,6,7}, 10, 7};
    int* p;
    displayArray(arr);
    std::cout << binarySearch(arr, 6) << std::endl;
    
}

I tried everything and still, it is not working for some reason am I missing something here?

CodePudding user response:

change position of l, h. you need to growth mid value if you find bigger value, the other way around, too.

CodePudding user response:

#include <iostream>
using  namespace std;

struct array1 {

    int A[10];
    int size;
    int length;
};


void displayArray(struct array1 arr) {
    std::cout << "the elements are :-" << std::endl << '\t';
    for (int i = 0; i < arr.length; i  ) {

        std::cout << arr.A[i] << ',';
    }
    std::cout << std::endl;

}

void binarySearch(struct array1 arr, int element) {

    int l, h;
    l = 0;
    h = arr.length;
    int mid = arr.length / 2;
   

    if (arr.A[mid] == element)
        cout << "i am on index number=" << mid;
    else if ( element< arr.A[mid])
        for (int i = 0; 1; i  )
        {
            if (arr.A[i] == element)
            {
                cout << "i am on index number=" << i;
                break;
            }
        }
    else
        for (int i = mid; 1; i  )
        {
            if (arr.A[i] == element)
            {
                cout << "i am on index number=" << i;
                break;
            }
        }


   
    

  

}

int main()
{
    struct array1 arr = { {1,2,3,4,5,6,7}, 10, 7 };
  
    displayArray(arr);
    binarySearch(arr, 6);
    return 0;
  •  Tags:  
  • c
  • Related