CS 250 Computer Programming and Problem Solving - FALL 1998 |
---|
[ Home | Syllabus | Notes | Glossary | CS250 WEB Version Home Page | Project Page | Final Study Guide]
Search an array for the smallest element.
int FindMin(int a[ ], int start, int end) // PRE: a is an array with elements defined between a[start] and a[end] // and start <= end // POST: return the location of the minimum value in the array between a[start] and a[end] { int min = a[start]; // guess it is the first element int where = start; // and remember where you found it for(int i = start+1; i <= end; i++) if(a[i] < min) { min = a[i]; where = i; } return where; }
const int NOT_FOUND = -1; // an impossible index value int Find(int a[ ], int x, int start, int end) // PRE: a is an array with elements defined between a[start] and a[end] // and start <= end // POST: return the location of the element "x" in the array between a[start] and a[end] // if exists, else return NOT_FOUND { for(int i = start; i <= end; i++) if(a[i] == x) return i; return NOT_FOUND; }
What is the element "x" is NOT in the list?
What if the element "x" IS in the list?
int RFind(int a[ ], int x, int start, int end) // PRE: a is an array with elements defined between a[start] and a[end] // and start <= end // Array "a" is sorted // POST: return the location of the element "x" in the array between a[start] and a[end] // if exists, else return where it should be placed { if(start == end) // one element arrays are easy (BASE CASE) return start; int middle = (start+end)/2; // find the middle of the sub- array if(x < a[middle]) // must be in the first "half" of the array return RFind(a,x,start,middle); // narrow the search to first half else if(x > a[middle]) must be in the second "half" return RFind(a,x,middle+1,end); else return middle; // here it is! }