Searchinginanarray
CS10003PROGRAMMINGANDDATASTRUCTURES
1
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
BasicConceptofLinearSearch
Basicidea
• Startatthebeginningofthe array.
• Inspectelementsonebyonetoseeif it matchesthekey.
• If amatchis found,returnthearray indexwherethematchwasfound.
• If nomatchis found,aspecialvalue is returned (like –1).
3
LinearSearch(contd.)
Function linear_search returns the 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
TimeComplexityofLinearSearch
Ameasureofhowmanybasicoperations analgorithm needstoperform beforeterminating.
Exampleofbasicoperation:match/ comparetwoelements.
• If therearenelementsinthearray:
• Bestcase:
matchfoundinfirst element(1 searchoperation)
• Worstcase:
nomatchfound,ormatchfoundinthe lastelement(nsearchoperations)
• Average case: (n+1)/ 2 searchoperations
5
Binary Search
6
BasicConcept
Binarysearchis applicableif the array 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
TheBasicStrategy
Whatdowewant?
• Plantofind thearray indexbetweenvalues 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
InitializationandReturnValue
int bin_search (int x[], 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
BinarySearchExamples
bin_search (x, 9, 3); binsearch(x, 9, 2);
-17 -5 3 6 12 21 45 63 50
Trace
0 1 2 3 4 5 6 7 8
Sortedarray
L R M key <= x[M]?
0 8 4 3 <= 12? [True]
0 4 2 3 <= 3? [True]
0 2 1 3 <= -5? [False]
2 2
key == x[L]?
[Loop terminates]
[True]
Wecanmodify thealgorithm bycheckingequalitywithx[mid].
L R M key <= x[M]?
0 8 4 2 <= 12? [True]
0 4 2 2 <= 3? [True]
0 2 1 2 <= -5? [False]
2 2
key == x[L]?
[Loop terminates]
[False]
10
AnotherVersionofIterative BinarySearch
int bin_search_1 (int x[], int size, int key)
{
int L, R, mid;
L = 0; R = size-1;
while (L <= R)
{
mid = (L + R) / 2;
if (key == x[mid]) return mid;
if (key < x[mid]) R = mid - 1;
else L = mid + 1;
}
return -1;
}
11
UnsortedvsSortedArraySearch:Where’sthedifference?
Supposethatthearray xhas1000elements.
Linear search
If keyis amemberofx, it wouldrequireabout500comparisons ontheaverage.
Binarysearch
• After 1stcompare,left with500elements.
• After 2ndcompare,left with250elements.
• After atmost10steps,you aredone.
12
TimeComplexity
If there arenelementsinthearray.
• Numberofiterations required:
log2n
Forn=64(say).
• Initially, list size=64.
• After firstcompare,list size=32.
• After secondcompare,list size=16.
• After thirdcompare,list size=8.
• …
• After sixthcompare,list size=1.
log264 =6
log21024 =10
2k=n,wherekisthe
numberofsteps.
13
Recursive VersionofBinarySearch
Thealgorithmforbinarysearchdirectlyleadstoarecursiveformulation.
• Thealgorithmis calledrecursively byadjustingtheleft orrightpointers,asapplicable.
• Thebaseconditionis:theelement is found,ortheleft andrightpointerscross.
14
int binarySearch (int x[], 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

Searching in dara structure and algorithm

  • 1.
  • 2.
    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
  • 3.
    BasicConceptofLinearSearch Basicidea • Startatthebeginningofthe array. •Inspectelementsonebyonetoseeif it matchesthekey. • If amatchis found,returnthearray indexwherethematchwasfound. • If nomatchis found,aspecialvalue is returned (like –1). 3
  • 4.
    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
  • 5.
    TimeComplexityofLinearSearch Ameasureofhowmanybasicoperations analgorithm needstoperformbeforeterminating. Exampleofbasicoperation:match/ comparetwoelements. • If therearenelementsinthearray: • Bestcase: matchfoundinfirst element(1 searchoperation) • Worstcase: nomatchfound,ormatchfoundinthe lastelement(nsearchoperations) • Average case: (n+1)/ 2 searchoperations 5
  • 6.
  • 7.
    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
  • 10.
    BinarySearchExamples bin_search (x, 9,3); binsearch(x, 9, 2); -17 -5 3 6 12 21 45 63 50 Trace 0 1 2 3 4 5 6 7 8 Sortedarray L R M key <= x[M]? 0 8 4 3 <= 12? [True] 0 4 2 3 <= 3? [True] 0 2 1 3 <= -5? [False] 2 2 key == x[L]? [Loop terminates] [True] Wecanmodify thealgorithm bycheckingequalitywithx[mid]. L R M key <= x[M]? 0 8 4 2 <= 12? [True] 0 4 2 2 <= 3? [True] 0 2 1 2 <= -5? [False] 2 2 key == x[L]? [Loop terminates] [False] 10
  • 11.
    AnotherVersionofIterative BinarySearch int bin_search_1(int x[], int size, int key) { int L, R, mid; L = 0; R = size-1; while (L <= R) { mid = (L + R) / 2; if (key == x[mid]) return mid; if (key < x[mid]) R = mid - 1; else L = mid + 1; } return -1; } 11
  • 12.
    UnsortedvsSortedArraySearch:Where’sthedifference? Supposethatthearray xhas1000elements. Linear search Ifkeyis amemberofx, it wouldrequireabout500comparisons ontheaverage. Binarysearch • After 1stcompare,left with500elements. • After 2ndcompare,left with250elements. • After atmost10steps,you aredone. 12
  • 13.
    TimeComplexity If there arenelementsinthearray. •Numberofiterations required: log2n Forn=64(say). • Initially, list size=64. • After firstcompare,list size=32. • After secondcompare,list size=16. • After thirdcompare,list size=8. • … • After sixthcompare,list size=1. log264 =6 log21024 =10 2k=n,wherekisthe numberofsteps. 13
  • 14.
    Recursive VersionofBinarySearch Thealgorithmforbinarysearchdirectlyleadstoarecursiveformulation. • Thealgorithmiscalledrecursively byadjustingtheleft orrightpointers,asapplicable. • Thebaseconditionis:theelement is found,ortheleft andrightpointerscross. 14
  • 15.
    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