answersLogoWhite

0

Binary search in array in c?

Updated: 8/10/2023
User Avatar

Wiki User

9y ago

Best Answer

// answer in C-style pseudo-code

// all division should be rounded up

// search will return the index of the number found, or -1 if it was not found

// nums is the array of numbers we're searching through

// num is the specific number we want to find in nums

// current is the index we are currently inspecting

// start is the first index of nums (typically 0)

// end is the last index of nums (typically the length - 1)

// preconditions: nums must be sorted or function is nondeterministic

int search( int[] nums, int num, int current, int start, int end ) {

if( nums[current] end ) { // target not in list

return -1;

}else if( nums[current] > num ) { // search to the left

return search( nums, num, current - ((current - start)/2), start, current );

}else if( nums[current] < num ) { // search to the right

return search( nums, num, current + ((end - current)/2), current, end );

}

}

// convenience function to start the search

int search( int[] nums, int num ) {

return search(nums, num, (nums.length/2), 0, nums.length - 1);

}

User Avatar

Wiki User

15y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

13y ago

#include

#include

void main()

{

int num,i,ar[20],m,low,high,mid,pos=1;

clrscr();

printf("Enter any number of element you want to insert=\t");

scanf("%d",&num);

printf("enter the list in non incresing order \n");

for(i=0;i

{

scanf("%d",&ar[i]);

}

printf("please enter the number you want to search\t");

scanf("%d",&m);

low=0;

high=num-1;

do

{

mid=(low+high)/2;

if(m

high=mid-1;

else if(m>ar[mid])

low=mid+1;

}while(m!=ar[mid]&&low<=high);

if(m==ar[mid])

{

printf("\nsearch sucessful");

}

else

{

printf("\nsearch unsuccessful");

}

getch();

}

iamr college of engineering

(rahul chaudhary)

cse branch(mail me at jaatchaudhary4@gmail.com)

This answer is:
User Avatar

User Avatar

Wiki User

9y ago

To perform a binary search upon an array, the array elements must be in sorted order.

int search (int value, int a[], const int size)

{

/*

returns the index of the given value,

or -1 if the value does not exist

*/

int left=0;

int right=size;

while (left<right)

{

int mid = (right-left)/2 + left;

if (a[mid]==value)

return mid;

else if (a[mid]<value)

left=mid+1;

else

right=mid;

}

return -1;

}

This answer is:
User Avatar

User Avatar

Wiki User

9y ago

The following program demonstrates binary search. Note that binary search only works with sorted data. To compare the performance, we'll use a standard linear search using unsorted data first, followed by a binary search on the same data in sorted order. The search functions will tell us how many elements had to be compared to locate the value. In rare cases a linear search may prove faster if the value being sought just happens to be near the start of the data. However, when a value cannot be found, the binary search is clearly faster since a linear search must search every element, whereas a binary search reduces the remaining data to be searched by half after each comparison.

Note that although it's easy to assume you need a binary tree to perform a binary search this is not the case at all. In order to search efficiently, you need a balanced binary tree and the simplest way of achieving that is with a sorted array. The middle element of a sorted array is the root of a binary tree and all searches begin there. If the value is not in the root, it must be in the left sub-array (if it is less) or the right sub-array (if it is greater), but each half of the array is simply a smaller binary tree where the middle element is the root of that tree. So by recursively comparing the roots you will either locate the value (in which case you are done) or you will end up with an empty sub-array (in which case the value does not exist).

To perform a binary search upon an array you need to keep track of the left and right indices of the sub-array. Initially these will represent the lower and upper bounds of the entire array. From these indices you can calculate the middle index. When you know which half of the sub-array your value resides, you move the left or right bound accordingly. Thus if the value is in the lower half, the right index becomes middle - 1, otherwise the left index becomes middle + 1. You then recalculate the middle index and continue searching. If left becomes greater than right then you have an empty sub-array so the value does not exist.

#include<iostream>

#include<iomanip>

#include<vector>

#include<algorithm>

#include<random>

#include<time.h>

void initialise (std::vector<unsigned>& data)

{

// Pseudo-random number generator (range: 1 to 99).

std::default_random_engine generator;

generator.seed ((unsigned) time (NULL));

std::uniform_int_distribution<unsigned> distribution (1, 99);

data.clear();

unsigned max_elements(50);

while (max_elements--)

data.push_back (distribution (generator));

}

int linear_search(std::vector<unsigned>& data, unsigned value, unsigned& comparisons)

{

int index(-1);

for( comparisons=0; comparisons<data.size() && index<0; ++comparisons)

if (data[comparisons] -1)

{

std::cout << "not found. ";

}

else

{

std::cout << "found at index " << binary_index << ". ";

}

std::cout << "Comparisons: " << binary_comparisons << std::endl;

}

}

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

include<stdio.h>

#include<conio.h>

void main()

{

int a[10],n,i,j,temp;

int beg,end,mid,target;

clrscr();

printf("enter the total numbers:");

scanf("%d",&n);

printf("enter the array elements:" );

for(i=0;i<n;i++)

scanf("%d",&a[i]);

for(i=0;i<n-1;i++)

{

for(j=0;j<n-i-1;j++)//for sorting the elements

{

If(a[j+1]<a[j])

{

temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

}

}

}

printf("the sorted numbers are:");

for(i=0;i<n;i++)

printf("%4d",a[i]);

beg=a[0];

end=a[9];

mid=(beg+end)/2;

printf("\nenter the number to be searched:");

scanf("%d",&target);

while(beg<=end && a[mid]!=target)//for searching the element in a sorted array

{

if(target<a[mid])

end=mid-1;

else

beg=mid+1;

mid=(beg+end)/2;

}

If(a[mid]==target)

{

printf("\nthe number is found at position %2d",mid);

}

else

{

printf("\nthe number is not found:");

}

getch();

}

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

C program for Performing Binary Search

http://thingsoverflow.com/?p=211

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Binary search in array in c?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

What search algorithm locates an item in an array by repeatedly dividing the array in half?

half means 1/2 from the whole (previous), which means 2 of 1/2, and 2 derived into binary. Ha, Binary Search is the term.


A binary search of an orderd set of elements in an array or a sequential search of the elements.Which one is faster?

A binary search is much faster.


Is it true In a binary search if the search fails to find the item on the first attempt then there are 999 elements left to search in an array of 1000 elements?

False. In a binary search, if the search fails on the first trial of an array of 1000 elements, then there are only nine more elements left to search.


Why binary search algorithm did not work on an unsorted array?

The binary search algorithm works by successively halving the array and determining which half the result lies in, or if the half-way point is the result. In order for that to work, the array must be in order, otherwise choosing the half-way point would be meaningless because it would not tell you which half of the array the result is located in.


Write a c program for binary searching?

/* C program for binary search: This code implements binary search in */ /* C language. It can only be used for sorted arrays, but it's fast as */ /* compared to linear search. If you wish to use binary search on an */ /* array which is not sorted then you must sort it using some sorting */ /* technique say merge sort and then use binary search algorithm to */ /* find the desired element in the list. If the element to be searched */ /* is found then its position is printed. */ #include&lt;stdio.h&gt; main() { int c, first, last, middle, n, search, array[100]; printf("Enter number of elements\n"); scanf("%d",&amp;n); printf("Enter %d integers\n", n); for ( c = 0 ; c &lt; n ; c++ ) scanf("%d",&amp;array[c]); printf("Enter value to find\n"); scanf("%d",&amp;search); first = 0; last = n - 1; middle = (first+last)/2; while( first &lt;= last ) { if ( array[middle] &lt; search ) first = middle + 1; else if ( array[middle] == search ) { printf("%d found at location %d.\n", search, middle+1); break; } else last = middle - 1; middle = (first + last)/2; } if ( first &gt; last ) printf("Not found! %d is not present in the list.\n", search); return 0; }

Related questions

What search algorithm locates an item in an array by repeatedly dividing the array in half?

half means 1/2 from the whole (previous), which means 2 of 1/2, and 2 derived into binary. Ha, Binary Search is the term.


A binary search of an orderd set of elements in an array or a sequential search of the elements.Which one is faster?

A binary search is much faster.


Is it true In a binary search if the search fails to find the item on the first attempt then there are 999 elements left to search in an array of 1000 elements?

False. In a binary search, if the search fails on the first trial of an array of 1000 elements, then there are only nine more elements left to search.


Why binary search algorithm did not work on an unsorted array?

The binary search algorithm works by successively halving the array and determining which half the result lies in, or if the half-way point is the result. In order for that to work, the array must be in order, otherwise choosing the half-way point would be meaningless because it would not tell you which half of the array the result is located in.


How do you represent binary search and linear search in graphics using c plus plus?

Linear search usually implies the data sequence is in an unsorted order or does not provide random access iterators (such as a list). Essentially you start from the beginning and traverse through each element until you find the element you are looking for, or reach the "one-past-the-end" iterator (which means the value does not exist). With binary search you use a sorted sequence, such as a sorted array. You start in the middle of the sequence. If the value is not there, you know which half of the array the value must be in, so you start in the middle of that half. By eliminating half the array (or sub-array) each time you will either find the value or you end up with an empty sub-array (which means the value does not exist). You can also use binary search on a binary tree which achieves the same thing, but the tree must be perfectly balanced (such as a red/black tree) to be of benefit.


What are strings in C?

an array of characters, usually terminated by a binary zero (0x00 or \0, not '0')


Write a c program for binary searching?

/* C program for binary search: This code implements binary search in */ /* C language. It can only be used for sorted arrays, but it's fast as */ /* compared to linear search. If you wish to use binary search on an */ /* array which is not sorted then you must sort it using some sorting */ /* technique say merge sort and then use binary search algorithm to */ /* find the desired element in the list. If the element to be searched */ /* is found then its position is printed. */ #include&lt;stdio.h&gt; main() { int c, first, last, middle, n, search, array[100]; printf("Enter number of elements\n"); scanf("%d",&amp;n); printf("Enter %d integers\n", n); for ( c = 0 ; c &lt; n ; c++ ) scanf("%d",&amp;array[c]); printf("Enter value to find\n"); scanf("%d",&amp;search); first = 0; last = n - 1; middle = (first+last)/2; while( first &lt;= last ) { if ( array[middle] &lt; search ) first = middle + 1; else if ( array[middle] == search ) { printf("%d found at location %d.\n", search, middle+1); break; } else last = middle - 1; middle = (first + last)/2; } if ( first &gt; last ) printf("Not found! %d is not present in the list.\n", search); return 0; }


Which are the searching algorithm always compare the middle element with the searching elements in the given array?

binary search system


How delete an array of object within the object in C?

First locate the position of an array by search after than use a delete function to delete an array


Complexity of an algorithm in data structure?

* search array =&gt; O(1) linked list=&gt; O(n) binary tree=&gt; O(log n) hash=&gt;O(1) * search array =&gt; O(1) linked list=&gt; O(n) binary tree=&gt; O(log n) hash=&gt;O(1)


What is the time complexity for searching an element in an array?

If the array is unsorted, the complexity is O(n) for the worst case. Otherwise O(log n) using binary search.


Best first search program in c?

The best search programs to attempt writing in C are the following: Linear search (simplest), Binary search (faster) Hash search (fastest).