Looking For Anything Specific?

ads header

How to construct or build binary search



 If you want to search  a number basically you prefer to do a linear search 

if you have some sorted numbers and your task is to find the specific number what will you do?

#include <stdio.h>

int linearSearch(int *arr, int length_arr, int n) {


for (int i = 0; i < length_arr; i++) {
if (arr[i] == n) {
return 1;
}
}

return 0;


}


int main() {
int num[5] = {1, 2, 3, 4, 5};
int length = sizeof(num) / sizeof(int);
printf("%d\n", linearSearch(num, length, 0));


return 0;
}




The time complexity of the above algorithm is 0(n), so that is not a problem. However, if you are dealing with millions of rows of data, we must consider the time. So you could use Binary Search, which engages divide and conquer. That is, if you have a problem, you must first break it down into smaller pieces.


Let's move on to how to create binary search algorithms.


int num[5] = {1, 2, 3, 4, 5};


Now I'm going to look for 2 in this array. So, since you already know that this array is sorted, I need to know whether this 2 is less than or greater than the mid element.


That is why I need to find a middle 

int mid = (low + high) / 2;


Then 

If the value is 2<3, we use recursion, which means we call the same method again and form the left array to search, but this time you have changed the high value to mid-1, which means we now search only lower to mid-1.



if (arr[mid] == n) {
return 1;
} else if (n<arr[mid]) {
binarySearch(arr, low, mid - 1, n);



so now low=0

high=2

so mid=1

arr[mid]==2 => true




 ok Now lets move to search 5 in a array 

we have to do same 

arr[mid]<5 so we are going to make right array 

 else if (n>arr[mid]) {
binarySearch(arr, mid + 1, high, n);
}



now we should change low value to mid+1;


if  you search 10 in array it may give so unexpected value so we have to control this method by 

putting some conditions


if (high < low) {
return 0;
}



then it stop searching 

and this method will work until to find   array[mid]==n  





here is the full coding

int binarySearch(int arr[], int low, int high, int n) {


if (high < low) {
return 0;
}
int mid = (low + high) / 2;

if (arr[mid] == n) {
return 1;
} else if (n<arr[mid]) {
binarySearch(arr, low, mid - 1, n);

} else if (n>arr[mid]) {
binarySearch(arr, mid + 1, high, n);
}


}

int main() {
int num[5] = {1, 2, 3, 4, 5};

printf("%d\n", binarySearch(num, 0, 4, 10));


return 0;
}












Post a Comment

1 Comments

  1. Nice blog! I really loved reading through this Blog... Thanks for sharing.......

    Inwizards Technology

    flutter app development
    flutter app development company

    ReplyDelete