Searching
Ref.: D.S. Malik, Data Structures Using C++
Searching
n size of the list f(n) the number of comparisons done by the search algorithm
Array-Based Lists
[0] [1] [2] [3] [4] [5] [6] [7] list 35 12 27 18 45 16 38
search for 27
compare 27 with list[0] compare 27 with list[1] compare 27 with list[2] X X
Array-Based Lists
search for 10
compare 10 with list[0] X keep going until there is no more data
Program fragment to find where item is in the list
int loc; bool found = false; for (loc = 0; loc < length; loc++) if (list[loc] == item) { found = true; break; } if found answer = loc; else answer = -1;
Unordered Linked Lists Program fragment to see if item is in the list
nodeType <Type> *current; bool found = false; current = first; while (current != NULL && !found) if (current->info == item) found = true; else current = current->link;
Ordered Linked Lists Program fragment to see if item is in the list
nodeType <Type> *current; bool found = false; current = first; while (current != NULL && !found) if (current->info >= item) found = true; else current = current->link; if (found) found = (current->info == item);
Doubly Linked Lists
e.g.
first last
struct nodeType { Type info; nodeType <Type> *next; nodeType <Type> *back; };
Program fragment to see if item is in an ordered list
nodeType <Type> *current; bool found = false; current = first; while (current != NULL && !found) if (current->info >= item) found = true; else current = current->next; if (found) found = (current->info == item);