Thread: Help with Binary Search Array in C

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    1

    Help with Binary Search Array in C

    Having trouble with program code. No errors detected from compiler; however, RUN always return "Target Found" even if target is not within the array. Any help in the right direction will be greatly appreciated.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define TRUE 1
    #define FALSE 0
    
    int iterativeBinary(int* arr, int left, int right, int target);
    
    int main()
    {
        int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int target = 0;
        int i = 0;
        
        printf("IND: ");
        for (i = 0; i <= 9; i++)
        {    
             printf("[%d] ", i);
        }
        
        printf("\nARR: ");
        for (i = 0; i <= 9; i++)
        {
            printf("[%d] ", arr[i]);
        }
        
        printf("\nSearch for Target: ");
        scanf("%d", &target);
            
        if (iterativeBinary == FALSE)
             printf("Target NOT found.\n");
        else
             printf("Target found.\n");
             
        system("pause");
        return 0;
    }
    
    int iterativeBinary(int* arr, int left, int right, int target)
    {
        int middle;
        while(left <= right && arr[middle] != target)
        {
             if(target > arr[middle])
                  left = middle + 1;
             else
                  right = middle - 1;
        }
        if (arr[middle] == target)
             return TRUE;
        else
            return FALSE;
        return;
    }
    Thank you.

  2. #2
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    iterativeBinary takes four arguments but you call it with no argument.

    Edit: you don't call it at all actually, you are comparing the iterativeBinary function pointer to 0. It's false so "Target found" is printed every time. I'm referring to this part here:

    Quote Originally Posted by simile View Post
    Code:
            
        if (iterativeBinary == FALSE)
             printf("Target NOT found.\n");
        else
             printf("Target found.\n");
    Last edited by Subsonics; 05-08-2011 at 01:15 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to do Binary search in 2Dimensional array
    By sureshcools in forum C Programming
    Replies: 4
    Last Post: 03-04-2011, 01:14 PM
  2. Binary Search of Array
    By pantherman34 in forum C Programming
    Replies: 21
    Last Post: 05-04-2010, 09:39 AM
  3. Binary Search Tree Using an array
    By mrsirpoopsalot in forum C++ Programming
    Replies: 11
    Last Post: 12-01-2009, 02:30 AM
  4. binary search in an array
    By brianptodd in forum C++ Programming
    Replies: 4
    Last Post: 11-12-2002, 02:05 PM
  5. Binary Search on an Array of Struct
    By curwa1 in forum C++ Programming
    Replies: 3
    Last Post: 10-25-2002, 02:02 PM