ca_quick_find.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright [2021] JD.com, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. #include "ca_quick_find.h"
  18. //二分查找
  19. int binary_search_header(NODE_HEADER *headers_ptr, const int low,
  20. const int high, const int key)
  21. {
  22. if (low > high) {
  23. return -1;
  24. }
  25. int mid_index = (low + high) / 2;
  26. if (key == headers_ptr[mid_index].bid) {
  27. while (1) {
  28. --mid_index;
  29. if (mid_index >= 0 &&
  30. key == headers_ptr[mid_index].bid) {
  31. continue;
  32. } else {
  33. mid_index += 1;
  34. break;
  35. }
  36. }
  37. return mid_index;
  38. } else if (key > headers_ptr[mid_index].bid) {
  39. return binary_search_header(headers_ptr, mid_index + 1, high,
  40. key);
  41. } else {
  42. return binary_search_header(headers_ptr, low, mid_index - 1,
  43. key);
  44. }
  45. }
  46. int binary_search_node(IP_NODE *app_set_ptr, const int low, const int high,
  47. const int key)
  48. {
  49. if (low > high) {
  50. return -1;
  51. }
  52. int mid_index = (low + high) / 2;
  53. if (key == app_set_ptr[mid_index].bid) {
  54. while (1) {
  55. --mid_index;
  56. if (mid_index >= 0 &&
  57. key == app_set_ptr[mid_index].bid) {
  58. continue;
  59. } else {
  60. mid_index += 1;
  61. break;
  62. }
  63. }
  64. return mid_index;
  65. } else if (key > app_set_ptr[mid_index].bid) {
  66. return binary_search_node(app_set_ptr, mid_index + 1, high,
  67. key);
  68. } else {
  69. return binary_search_node(app_set_ptr, low, mid_index - 1, key);
  70. }
  71. }