Binary search is a fundamental algorithm in computer science. It is used to find the position of a given integer in a sorted list of integers. We don't have to iterate through the whole list, if we use this algorithm. Therefore it is an efficient algorithm for searching. The complexity of binary search algorithm is O(logN).
http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBinarySearch.html
If N elements are there in the list,
you will have to halve the list x times to find an element. (Halve the list until 1 element is left)
1 = N / 2x
2x = N
x = log2 N
Therefore time complexity - O(logN)
[code]
#include <stdio.h>
int main()
{
int arr[100];
int n, i, el;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Enter the elements\n");
for(i = 0; i<n; i++)
{
scanf("%d",&arr[i]);
if(i != 0 && arr[i-1]>arr[i])
{
printf("Please enter a sorted list!\n");
return 0;
}
}
printf("Enter the element to search\n");
scanf("%d",&el);
int position = binarySearch(arr,n,el);
if(position != -1)
printf("The element is at %d.\n",position);
else
printf("Element not found!\n");
return 0;
}
/*Binary search function
Arguments - integer array
size of the array
element to search for
Return the position if successful
*/
int binarySearch(int arr[], int size, int el)
{
int low = 0, high = size-1;
int mid = (high + low)/2;
while(arr[mid] != el)
{
if(arr[mid] > el)
high = mid;
else
low = mid;
if(high == low+1)
{
if(arr[high] == el)
return high;
else if(arr[low] == el)
return low;
else
return -1;
}
mid = (low + high)/2;
}
return mid+1;
}[/code]
Subscribe to:
Post Comments (Atom)
Optimized quick sort
In the previous article we discussed about quick sort algorithm. In this article we are going to discuss about further optimizing quick sor...
-
Alcohol is a very ancient drink that has been consumed for thousands of years by almost all civilizations. Alcoholic beverages are an import...
-
Cell phones' electromagnetic radiation is said to cause brain cancer. Is it true? People are concerned about the fact that high levels...
-
Einstein's Theory of Relativity was published in the year 1905 as the most general explanation of nature and its phenomenon. Einstein ba...
No comments:
Post a Comment