gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
用c++实现二分排序算法
- User
用c++实现二分排序算法
- Assistant
下面是使用C++实现的二分查找算法的示例代码:
#include <iostream> using namespace std; int binarySearch(int arr[], int low, int high, int target) { while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return -1; } void binarySort(int arr[], int size) { for (int i = 1; i < size; i++) { int key = arr[i]; int j = i - 1; int insertIndex = binarySearch(arr, 0, j, key); while (j >= insertIndex) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { cout << arr[i] << " "; } cout << endl; } int main() { int arr[] = {9, 5, 7, 1, 4, 3, 8, 2, 6}; int size = sizeof(arr) / sizeof(arr[0]); cout << "Original array: "; printArray(arr, size); binarySort(arr, size); cout << "Sorted array: "; printArray(arr, size); return 0; }该代码中,函数实现了二分查找算法,接受一个有序数组以及目标值作为参数,在数组中查找目标值,并返回该值在数组中的索引,如果找不到,则返回-1。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.