Binary Search
The method is based on the Divide-Conquer algorithmic strategy.
- Precondition For Binary Search
- Data must be organized in a linear way.
- Data has to be in the sorted oder in either ascending or decending order.
- Advantages of Binary Serach
- Worst case time complexity is O(log2n), which is very efficient compared to linear search O(n).
- Disadvantages of Binary Search
- Data has to be in sorted order.
- Complexity of Binary Search
Best Case:-The key is found at the middle position after 1 comparision.
-The best case time complexity is Ω(1).
Worst Case:-The Worst case time complexity is O(log2n).
CODE
👇
- #include <stdio.h>
- int main()
- {
- int first, middle,last, n, i, search, a[100];
- setbuf(stdout, NULL);
- printf("ENTER THE SIZE OF ARRAY:");
- scanf("%d", &n);
- printf("ENTER %d ELEMENT IN ASCENDING ORDER:\n",n);
- for(i=0; i<n; i++)
- scanf("%d", &a[i]);
- printf("ENTER THE VALUE TO BE SEARCH:\n");
- scanf("%d", &search);
- first=0;
- last=n-1;
- middle=(first+last)/2;
- while(first <= last)
- {
- if(a[middle]<search)
- first = middle + 1;
- else if(a[middle] == search)
- {
- printf("ELEMENT FOUND AT INDEX %d.\n",middle);
- break;
- }
- else
- last = middle - 1;
- middle = (first + last)/2;
- }
- if(first > last)
- printf("ELEMENT NOT FOUND IN THE LIST.\n");
- return 0;
- }
👉Execute👈
//Output
/*
1]
ENTER THE SIZE OF ARRAY:5
ENTER 5 ELEMENT IN ASCENDING ORDER:
1
3
5
7
9
ENTER THE VALUE TO BE SEARCH:
5
ELEMENT FOUND AT INDEX 2.
2]
ENTER THE SIZE OF ARRAY:5
ENTER 5 ELEMENT IN ASCENDING ORDER:
1
3
5
7
9
ENTER THE VALUE TO BE SEARCH:
8
ELEMENT NOT FOUND IN THE LIST.
*/
//ThE ProFessoR
Thanks for this code 😊 and your support..
ReplyDelete