fork(2) download
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3. #include <stdlib.h>
  4. #include <assert.h>
  5. #include <time.h>
  6.  
  7. bool binarysearch(int value, int values[], int n, int lo, int hi) {
  8. int mid = (hi + lo) / 2;
  9. if (lo <= hi) {
  10. if (values[mid] == value) {
  11. printf("Value found %d at index %d \n", value, mid);
  12. return true;
  13. }
  14. else if (values[mid] > value)
  15. return binarysearch(value, values, n, lo, mid);
  16. else
  17. return binarysearch(value, values, n, mid + 1, hi);;
  18. }
  19. else return 0;
  20. }
  21. /* Returns an integer in the range [0, n).
  22.  *
  23.  * Uses rand(), and so is affected-by/affects the same seed.
  24.  */
  25. int randint(int n) {
  26. if ((n - 1) == RAND_MAX) {
  27. return rand();
  28. } else {
  29. // Chop off all of the values that would cause skew...
  30. long end = RAND_MAX / n; // truncate skew
  31. assert (end > 0L);
  32. end *= n;
  33.  
  34. // ... and ignore results from rand() that fall above that limit.
  35. // (Worst case the loop condition should succeed 50% of the time,
  36. // so we can expect to bail out of this loop pretty quickly.)
  37. int r;
  38. while ((r = rand()) >= end);
  39.  
  40. return r % n;
  41. }
  42. }
  43. main() {
  44. int i, n, value;
  45. int values[] = {1, 2, 3, 4, 5, 6};
  46.  
  47. int hi = values[n - 1];
  48. int lo = values[0];
  49. srand(time(NULL));
  50. int random = rand() % 14;
  51. if (!binarysearch(random, values, n, 0, 5))
  52. printf("Number %d not present in array\n", random);
  53. }
Success #stdin #stdout 0s 2160KB
stdin
Standard input is empty
stdout
Number 9 not present in array