0% found this document useful (0 votes)
33 views2 pages

Searches

The document describes four algorithms for searching arrays: binary search, linear search, recursive binary search, and recursive linear search. Binary search and linear search are iterative algorithms that search sorted and unsorted arrays, respectively, by comparing elements to a target key. Recursive binary search and recursive linear search are recursive implementations of the iterative algorithms that break the search space in half on each recursive call.

Uploaded by

smithieallstar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views2 pages

Searches

The document describes four algorithms for searching arrays: binary search, linear search, recursive binary search, and recursive linear search. Binary search and linear search are iterative algorithms that search sorted and unsorted arrays, respectively, by comparing elements to a target key. Recursive binary search and recursive linear search are recursive implementations of the iterative algorithms that break the search space in half on each recursive call.

Uploaded by

smithieallstar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

Binary Search Algorithm

int binarySearch(int sortedArray[], int first, int last, int key)


{

while (first <= last)


{
int mid = (first + last) / 2; // compute mid point.
if (key > sortedArray[mid])

first = mid + 1; // repeat search in top half.

else if (key < sortedArray[mid])

last = mid - 1; // repeat search in bottom half.


else
return mid; // found it. return position /////
}
return -(first + 1); // failed to find key
}

Linear Search Algorithm


nt linearSearch(int a[], int first, int last, int key)
{

for (int i=first; i<=last; i++)


{
if (key == a[i])
{
return i;
}
}
return -1; // failed to find key
}
Recursive Binary Search Algorithm
int rBinarySearch(int sortedArray[], int first, int last, int key)
{

if (first <= last)


{
int mid = (first + last) / 2; // compute mid point.
if (key == sortedArray[mid])
return mid; // found it.
else if (key < sortedArray[mid])
// Call ourself for the lower part of the array
return rBinarySearch(sortedArray, first, mid-1, key);
else
// Call ourself for the upper part of the array
return rBinarySearch(sortedArray, mid+1, last, key);
}
return -(first + 1); // failed to find key
}

Recursive Linear Search Algorithm


not sure
int linearSearch(int array[],int counter)

{
--counter;

if (counter < 0)
return -1;
if (array[counter] == 10)
return (counter+1);
else
return linearSearch(array,counter);

You might also like