Searching
An Introduction with Examples |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
/** * Linear Search */ int search(const int a[], int n, int target) { int i; i = 0; while ((i < n) && (a[i] < target)) i++; if (a[i] == target) return 1; else return 0; }
/** * Binary Search */ int search(const int a[], int n, int target) { int i, lower, upper; lower = 0; upper = n - 1; i = upper/2; while ((lower <= upper) && (a[i] != target)) { if (target > a[i]) lower = i + 1; else upper = i - 1; i = (lower + upper)/2; } if (a[i] == target) return 1; else return 0; }
/** * One Way to Setup for the Constant Time Search */ int i; int a[n], indicator[m]; . . . for (i=0; i < m; i++) { indicator[i] = 0; } for (i=0; i < n; i++) { indicator[a[i]] = 1; }
return indicator[a[i]];
/** * Another way to setup for the Constant Time Search */ int i, j, prev; int a[n], indicator[m]; . . . prev = 0; for (i=0; i < n; i++) { for (j=prev; j < a[i]; j++) { indicator[j] = 0; // How many times is this done? } indicator[a[i]] = 1; prev = a[i] + 1; // How many times is this done? }