Searches

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 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