Datastruct Notes # 2
Datastruct Notes # 2
Note: don’t forget to break the loop if item An abstract diagram of a linked list:
is already found.
Component Link
ALGORITHM [BINARY SEARCH] (Data) (Location of next
Steps: node)
1. [Initialize segment variables] set:
First = LB Head – starting index
Last = UB
Mid = (First+Last)/2 Linked list represented as an array:
2. Repeat steps 3 and 4 while first<=last
and A[Mid] != ITEM Struct NodeType {
3. If ITEM<A[Mid], set last = mid – 1 int component;
Else, set first = mid + 1 [end of if int link;
structure] };
4. Set mid = (first+last)/2
[end of step 2 loop] NodeType list[1000];
5. If A[Mid} == ITEM, set Loc = Mid int head;
Else, set Loc = Null [end of structure]
6. Exit
Linked list sample code:
RECURSIVE ALGORITHM [BINARY
SEARCH]
#include <stdio.h>
procedure binary search(x,i,j)
m: =[(i+j)/2] struct list {
if x = am, then char letter;
location = m struct list * next;
else if (x<am and i<m), then } a,b,c,d,e;
binary search(x,i,m-1)
else if (x>am and j>m), then int main() {
binary search(x ,m+1,j) struct list *list_pointer = &a;
else location = 0 int count = 0;
DANGLING POINTER
- a pointer that points to a variable that
has been deallocated.
*ptr2 = 44;
*ptr1 = *ptr2;
delete ptr1; //to avoid an inaccessible object
ptr1 = ptr2;
delete ptr2;
ptr1 = NULL; // to avoid a dangling pointer
}