Searching
Checkif agiven element(calledkey)occursinthe array.
• Example:arrayofstudentrecords; rollno canbethe key.
Twomethodstobediscussed:
a) If thearray elementsareunsorted.
• Linear search
b) If thearray elementsaresorted.
• Binarysearch
2
LinearSearch(contd.)
Function linear_search returnsthe array indexwhereamatchis found.
It returns–1if there is nomatch.
int linear_search (int a[], int size, int key)
{
int pos = 0;
while ((pos < size) && (key != a[pos]))
pos++;
if (pos < size)
return pos;
return -1;
/* Return the position of match */
/* No match found */
}
4
BasicConcept
Binarysearchis applicableif thearray is sorted.
BasicIdea
• Lookfor the targetinthe middle.
• If youdon’tfindthe key, you canignore half ofthearray, andrepeatthe process withthe
other half.
Ineverystep,wereduce,byafactor oftwo,thenumberofelementstosearchfrom.
7
8.
TheBasicStrategy
Whatdowewant?
• Plantofind thearrayindexbetweenvalues larger andsmaller thankey:
• Lookatthe elementatindex[(L+R)/2].
• Discardonehalf ofthesearchwindowdependingonthe outcomeoftest.
0
<= key > key
x:
L
• Situationwhilesearching:
• Initially, the searchwindowis theentire array, thatis, LandRareinitialized tothe
indicesofthe first andthelastelements.
n-1
R
8
9.
InitializationandReturnValue
int bin_search (intx[], int size, int key)
{
int L, R, mid;
L = 0; R = size - 1;
while (L != R)
{
mid = (L + R) / 2;
If key
locatio
If not
appears inx[0…size–1],return its
n,possuchthatx[pos]==key.
found,return –1
}
if (key <= x[mid])
else L = mid + 1;
}
if (key == x[L])
return L;
else
return -1;
R = mid;
9
int binarySearch (intx[], int L, int R, int key)
{
// If the element is present at the middle
int mid;
if (L <= R) {
mid = (L + R) / 2;
if (key == x[mid])
return mid;
if (key < x[mid]) // Look into the left subarray
else
return binarySearch (x, L, mid-1, key);
// Look into the right subarray
return binarySearch (x, mid+1, R, key);
}
// Element is not present in array
return -1;
}
int result = binarySearch (arr, 0, n-1, key);
if (result == -1)
printf ("Key is not present in arrayn");
else
printf("Key is present at index %dn", result);
Returns locationofkeyingivenarray
arr[L …R]if present, otherwise–1
15