Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
2.5 kB
2
Indexable
Never
/// Binary search in main

#include <stdio.h>
#include <stdlib.h>

int main(void)
{

    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);

    // creating new array
    int arr_sorted[size_arr];
    for(int i = 0; i < size_arr; i++){
        arr_sorted[i] = arr[i];
    }
    // Bubble sort for arr_sorted
    int flag = 1;
    while(flag != 0){
        flag = 0;
        for(int i = 0; i < size_arr; i++){
            for(int j = 0; j < size_arr - i - 1; j++){
                if(arr_sorted[i] > arr_sorted[i+1]){
                    int temp = arr_sorted[i];
                    arr_sorted[i] = arr_sorted[i+1];
                    arr_sorted[i+1] = temp;
                }
            }
        }
    }


    printf("Original Array\n");
    printf("{");
    for(int i = 0; i < size_arr; i++){
        printf("%d", arr[i]);
        if(i < size_arr - 1){
            printf(",");
        }
    }
    printf("}");

    puts("");
    printf("Sorted Array\n");
    printf("{");
    for(int i = 0; i < size_arr; i++){
        printf("%d", arr_sorted[i]);
        if(i < size_arr - 1){
            printf(",");
        }
    }
    printf("}");

    puts("");

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

    while(first <= last){
        if(arr_sorted[mid] == search){
            printf("%d is at location %d of the sorted array.", search, mid+1);
            break;
        }
        else if(arr_sorted[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");
        }
    }

//    // Find element in original array
//    for(int i = 0; i < size_arr; i++){
//        if(arr_sorted[])
//    }

    return 0;
}