Searching is very important in data structure. Here is the code of Binary Search.......
#include <stdio.h>
int main()
{
int ara[16] ={1, 4, 6, 8, 9, 11, 14, 15, 20, 25, 33, 83, 87, 97, 99, 100},
int low = 0,high = 15, mid, num = 15;
while (low <= high)
{
mid = (low + high) / 2;
if (num == ara[mid])
{
break;
}
if (num < ara[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
if (low > high)
{
printf("%d is not in the array.\n", num);
}
else
{
printf("%d is found in the array. It is the %d th element of the array.\n", ara[mid], mid);
}
return 0;
}
#include <stdio.h>
int main()
{
int ara[16] ={1, 4, 6, 8, 9, 11, 14, 15, 20, 25, 33, 83, 87, 97, 99, 100},
int low = 0,high = 15, mid, num = 15;
while (low <= high)
{
mid = (low + high) / 2;
if (num == ara[mid])
{
break;
}
if (num < ara[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
if (low > high)
{
printf("%d is not in the array.\n", num);
}
else
{
printf("%d is found in the array. It is the %d th element of the array.\n", ara[mid], mid);
}
return 0;
}
0 comments:
Post a Comment