/* search.cpp David Klick CIS 250 1/31/05 demonstration of linear and binary search */ #include #include #include using std::cout; using std::endl; const int SIZE = 40000; void quickSort(int*, int); void q_sort(int*, int, int); int linsearch(int, int*, int); int binsearch(int, int*, int); int main(void) { int num[SIZE]; int i, hits, misses; srand(time(NULL)); // create array of random ints (not in order) // note: some compilers will not allow ints this large for (i=0; i= lo) { middle = (hi + lo) / 2; if (arr[middle] == k) return middle; else if (arr[middle] > k) hi = middle - 1; else lo = middle + 1; } return -1; } void quickSort(int a[], int len) { q_sort(a, 0, len-1); } void q_sort(int a[], int left, int right) { int pivot, l_hold, r_hold; l_hold = left; r_hold = right; pivot = a[left]; while (left < right) { while ((a[right] >= pivot) && (left < right)) right--; if (left != right) a[left++] = a[right]; while ((a[left] <= pivot) && (left < right)) left++; if (left != right) a[right--] = a[left]; } a[left] = pivot; pivot = left; left = l_hold; right = r_hold; if (left < pivot) q_sort(a, left, pivot-1); if (right > pivot) q_sort(a, pivot+1, right); }