You are on page 1of 11

Searching Algorithm

Algorithms that accepts an argument a and


tries to find record whose key is a.
Sequential Search

⚪ This algorithm searches from left to right and checks whether seeking
element are in the list
⚪ Search in sorted list
⚪ Search in unsorted list
⚪ It is applicable to array or linked list

Searching
Sequential Search
1. Set j = 1
2. if (x = aj) algorithm terminate successfully
3. Increase j by 1
4. If (j≤n) back to 2, otherwise algorithm terminate
unsuccessfully

Searching
Reordering a List for
Maximum Efficiency

⚪ Move-to-front-method
● Efficient only for linked list
● the record is removed from its current
position and placed at the head of the list

⚪ Transposition method
successfully retrieved record is interchange with record that
immediately precedes it

Searching
Argument key is possible:
•In almost end position

•absent from list

SEARCH IN ORDERED
TABLE

Searching
Index Sequential Search

Auxiliary table 321 1 115


Each index element consist of 592 4 321
a key kindex and pointer to 876 7 409
element in the file 540
pindex 592
kindex
602
741
For (i=0; i<indsize && kindex(i)≤key; i++); 876
lowLim=(i==1)? 0 : pindex(i+1);
//if (i=1) then lomLim=0 else lomLim=pindex(i-1);
hiLim=(i==indsize)? n-1 : pindex(i)-1;
For (j=lowLim; j<hiLim && k(j)≠key; j++);
Return ((j>hiLim) ? -1 : j)
Searching
Binary Search

⚪ Binary search could be use where its element is in sorted order


⚪ This start by comparing x to the middle key and the result tells which
half table should be search next

Searching
Binary Search

⚪ The algorithm
lo=0; hi=n-1
while (lo ≤ hi) {
mid=(lo+hi)/2;
if (key==k(mid)) return mid;
if (key<k(mid)) hi=mid-1;
else lo=mid+1;
}
return -1;

Searching
Binary Search (example)
n=13; lo=0; hi=13-1=12; mid=(0+12)/2; key=512;

exampl 61 87 154 170 275 426 503 512 612 653 765 897 908
e:
lo hi
amid<key 🡪lo=mid+1=7; mid=(7+12)/2=9;
61 87 154 170 275 426 503 512 612 653 765 897 908

amid>key 🡪 hi=mid-1=8; mid=(7+8)/2=7; lo hi


61 87 154 170 275 426 503 512 612 653 765 897 908

lo hi
amid=key 🡪 terminate

Searching
Recursive Binary Search

⚪ The algorithm
binSearch(lo,hi);
//lo=0; hi=n-1
while (lo ≤ hi) {
mid=(lo+hi)/2;
if (key==k(mid)) return mid;
if (key<k(mid)) binSearch(lo, mid-1);
else binSearch(mid+1,hi);
}
return -1;

Searching
⚪ Buat aplikasi untuk
● Sequential Search (array/list)
● Move to front(array/list)
● Transposition (arrray/list)
● Index sequential in array
● Binary Search in array
● Recursive Binary Search in array
⚪ Untuk masing2 algoritma, hitung jumlah pembandingan dan
penugasan

Searching

You might also like