Untitled

 avatar
unknown
plain_text
4 years ago
1.3 kB
5
Indexable
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    /// Binary search in main

    int first, last, mid, search, size_arr;
    int count = 0;

    printf("Please enter the size of an array: ");
    scanf("%d", &size_arr);
    int arr[size_arr]; //create array

    printf("Please enter %d elements of an array as shown below.\n");
    while(count < size_arr){
        printf("Element %d: ", count + 1);
        int element;
        scanf("%d", &element);
        arr[count] = element;
        count++;
    }

    printf("Input the number that you want to search: ");
    scanf("%d", &search);

    first = 0;
    last  = count;
    mid = (count - first)/2;

    while(first <= last){
        if(arr[mid] == search){
            printf("%d is at location %d of the array.", search, mid+1);
            break;
        }
        else if(arr[mid] < search){ // If element is larger than middle
            first = mid + 1;
        }
        else{ // If element is smaller than middle
            last = mid - 1;
        }
        mid = (first + last)/2;

        if(first > last){ // Element not in array
            printf("Element is not found in the array.\n");
        }
    }

    return 0;
}
Editor is loading...