Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
1.8 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>

int binarySearch(int arr[], int l, int r, int search);


int main(void){
    int count = 0, search;

    printf("Please enter the size of an array: ");
    int size_arr;
    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++;
    }

    // Bubble sort
    for(int i = 0; i < size_arr; i++){
        for(int j = 0; j < size_arr - i - 1; j++){
            if(arr[j] > arr[j+1]){
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
    puts("");
    printf("Please enter the element that you want to search: ");
    scanf("%d", &search);

    int index = binarySearch(arr, 0, size_arr, search);
    if(index != -1){
        printf("%d is the %d-th element of the ascending array.\n", search, index);
    }
    else{
        printf("The element is not within the array.\n");
    }


    return 0;
}

int binarySearch(int arr[], int l, int r, int search){
    if(r >= l){
        int mid = (l + (r - 1)/2); //r-1 because of the index
        if(arr[mid] == search){ //If element is in mid, return mid
            return mid;
        }
        if(arr[mid] > search){ // If element is smaller than mid
            return binarySearch(arr, l, mid - 1, search); // r = mid - 1
        }
        else{ // If element is larger than mid
            return binarySearch(arr, mid + 1, r, search); // l = mid + 1
        }
    }
    return -1; // return -1 if element isn't in array
}