您的位置:首页 > 科技 > 能源 > 数据结构——二分算法

数据结构——二分算法

2024/11/18 3:42:04 来源:https://blog.csdn.net/qq_68915288/article/details/139939387  浏览:    关键词:数据结构——二分算法

二分查找

1. 在排序数组中查找元素的第一个和最后一个位置


代码实现:

/*** Note: The returned array must be malloced, assume caller calls free().*/int binarySearch(int *nums, int numsSize, int target) {int l = 0, r = numsSize - 1;         while (l <= r) {int mid = (l + r) >> 1;if (nums[mid] == target) {            return mid;} else if (nums[mid] > target) {      r = mid - 1;} else if (nums[mid] < target) {      l = mid + 1;}}return -1;
}int* searchRange(int *nums, int numsSize, int target, int *returnSize) {int *res = malloc(sizeof(int) * 2);memset(res, -1, sizeof(int) * 2);*returnSize = 2;if (nums == NULL || numsSize < 1) {return res;}int ind = binarySearch(nums, numsSize, target);if (ind == -1) {return res;}int i, j;for (i = ind - 1; i >= 0; i--) {if (nums[i] != target) {break;}}res[0] = i + 1;for (j = ind + 1; j < numsSize; j++) {if (nums[j] != target) {break;}}res[1] = j - 1;return res;
}

2. 搜索插入位置

代码实现:

/*函数功能:返回有n个元素的数组arr中,找等于key或者第一个比key大的数的下标
*/
int binary_search_v1(int *arr, int n, int key) {int head = 0, tail = n - 1, mid; // 左闭右闭while (head <= tail) {mid = (head + tail) >> 1;if (key > arr[mid]) {head = mid + 1;} else if (key < arr[mid]) {tail = mid - 1;} else if (key == arr[mid]) {return mid;}}return head;
}int binary_search_v2(int *arr, int n, int key) {int head = 0, tail = n, mid; // 左闭右开while (head < tail) {mid = (head + tail) >> 1;if (key > arr[mid]) {head = mid + 1;} else if (key < arr[mid]) {tail = mid;} else if (key == arr[mid]) {return mid;}}return head;
}
int binary_search_v3(int *arr, int l, int n, int key) {int head = l, tail = n; // 左闭右开int mid = (head + tail) >> 1;if (head >= tail) {return head;}if (key > arr[mid]) {head = mid + 1;} else if (key < arr[mid]) {tail = mid;} else if (key == arr[mid]) {return mid;}return binary_search_v3(arr, head, tail, key); 
}int searchInsert(int *nums, int numsSize, int target) {return binary_search_v1(nums, numsSize, target);// return binary_search_v2(nums, numsSize, target);// return binary_search_v3(nums, 0, numsSize, target);
}

3. 二分查找

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com