fork(2) download
  1. #include <stdio.h>
  2.  
  3. int BinarySearch(double *vals, int size, double ref);
  4.  
  5. int main(void) {
  6. // list to be searched (sorted)
  7. double vals[] = { 2.718, 3.14, 6.022, 10.23 };
  8. int size = sizeof(vals)/sizeof(vals[0]);
  9.  
  10. // list where each value is searched
  11. double chks[] = { 2.0, 3.13, 3.14, 3.15, 15.0 };
  12. int num = sizeof(chks)/sizeof(chks[0]);
  13.  
  14. for(int idx=0; idx<num; idx++) {
  15. int pos = BinarySearch(vals, size, chks[idx]);
  16. if (pos >= 0) {
  17. printf("pos = %d, %f for %f\n", pos, vals[pos], chks[idx]);
  18. } else {
  19. printf("not found for %f\n", chks[idx]);
  20. }
  21. }
  22. return 0;
  23. }
  24.  
  25. int BinarySearch(double *vals, int size, double target) {
  26. int start = 0;
  27. int end = size - 1;
  28. int mid;
  29.  
  30. if (target < vals[start] || target > vals[end]) {
  31. return -1;
  32. }
  33.  
  34. while (start <= end) {
  35. mid = (start + end) / 2;
  36. if (mid == (start+1) && (target >= vals[start]) && (target < vals[mid])) {
  37. return start;
  38. } else if (target < vals[mid]) {
  39. end = mid - 1;
  40. } else {
  41. start = mid + 1;
  42. }
  43. }
  44.  
  45. if (end < start) {
  46. return end;
  47. }
  48. return start;
  49. }
  50.  
  51.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
not found for 2.000000
pos = 0, 2.718000 for 3.130000
pos = 1, 3.140000 for 3.140000
pos = 1, 3.140000 for 3.150000
not found for 15.000000