二分法查+范围内临近值查找
1 uint16 FindPosition(uint8 arr[], uint16 length, uint8 target) 2 { 3 uint16 low = 0; 4 uint16 high = length - 1; 5 uint16 closest_position = 0xFFFF; 6 7 if (target < arr[0] || target > arr[length - 1]) 8 { 9 return 0xFFFF; // target不在数组范围内 10 } 11 12 while (low <= high) 13 { 14 uint16 mid = low + (high - low) / 2; 15 16 if (arr[mid] == target) 17 { 18 return mid; 19 } 20 else if (arr[mid] < target) 21 { 22 closest_position = mid; // 更新最接近且小于target的位置 23 low = mid + 1; 24 } 25 else 26 { 27 high = mid - 1; 28 } 29 } 30 31 return closest_position; // 返回最接近且小于target的位置 32 }
1 int main(int argc, char *argv[]) 2 { 3 uint8 arr[] = {1, 3, 5, 7, 10, 11, 13,17, 20, 23, 29,32,40,49}; 4 uint16 length = sizeof(arr) / sizeof(arr[0]); 5 uint8 target = 14; 6 7 uint16 position = FindPosition(arr, length, target); 8 9 if (position != 0xFFFF) 10 { 11 printf("Closest position less than target found at position: %d\n", position); 12 } 13 else 14 { 15 printf("Target not in range\n"); //result:6 16 } 17 //system("pause"); 18 return 0; 19 }