chatgptHello! How may I assist you today使用C语言编程从键盘输入一整数将一维数组进行排序然后在一个整型一维数组 a20中用折半查找法找出该数是数 组中第几个元素的值。如果该数不在数组中则打印No found。
好的,下面是C语言代码实现:
#include <stdio.h>
int binary_search(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
void bubble_sort(int arr[], int n) {
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int target;
printf("请输入一个整数:");
scanf("%d", &target);
int arr[20];
printf("请输入20个整数:");
for (int i = 0; i < 20; ++i) {
scanf("%d", &arr[i]);
}
bubble_sort(arr, 20);
int index = binary_search(arr, 20, target);
if (index != -1) {
printf("%d 是数组中第 %d 个元素的值。\n", target, index + 1);
} else {
printf("No found\n");
}
return 0;
}
以上代码中,我们首先使用 scanf 函数从键盘输入一个整数 target,然后再从键盘输入 20 个整数,存储到一维数组 arr 中。
接下来,我们使用冒泡排序算法对 arr 进行排序,然后使用折半查找算法在 arr 中查找 target,返回 target 在 arr 中的下标,如果 target 不在 arr 中,则返回 -1。
最后,根据返回的下标判断 target 是否在 arr 中,如果在,则输出 target 是数组中第几个元素的值,否则输出 "No found"
原文地址: https://www.cveoy.top/t/topic/ccjN 著作权归作者所有。请勿转载和采集!