gpt4 book ai didi

c - C中数组的冒泡排序和二分查找的组合代码问题

转载 作者:行者123 更新时间:2023-12-04 09:57:17 25 4
gpt4 key购买 nike

我试图使用冒泡排序对用户输入数组进行排序,然后进行二分搜索以找到某个键​​。

然而,每个代码本身都可以正常工作,但是当我将它们组合起来时,二进制搜索不起作用:当我输入搜索键时,它会对数组进行排序并给出输出,但始终找不到该键。我试图添加一个 break第一个 if 之后的语句在 while但它也不起作用

#include <stdio.h>

int main(void) {
int arr[100];
int temp, size ,first, last, middle ,search,found,result;

printf("Enter the array size: ");
scanf("%d",&size);
printf("Enter the array elements: ");

for(int i = 0 ; i <size ;++i )
{
scanf("%d",&arr[i]);
}
printf("Enter search value: ");
scanf("%d", &search);

for(int i = 0 ; i<size ; ++i)
for(int j= 0; j<size-1; j++)
{
if(arr[j+1]>arr[j])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}

printf("Elements of the array sorted in descending order: ");
for(int i = 0;i <size ;++i)
{
printf("%d ", arr[i]);
}

printf("\n");
printf("Number of passes is: %d", size -1);

first = 0;
last = size- 1;
found = 0;

while (!found &&first <= last) {
middle = (first+last)/2;

if ( search == arr[middle] )
{
found = 1 ;
result = middle;
break;
}
else if(search < arr[middle])
{
last = middle - 1;
}

else
first = middle +1;
}

if (found)
{
printf("\n");
printf("%d found at location %d.\n", search, result);
}
else
{
printf("\n");
printf("%d is not found", search);
}

return 0;
}

最佳答案

将小于运算符 ( < ) 替换为大于运算符 ( > ),因为较大的元素位于中间的左侧。

else if(search < arr[middle]) //replace '<' to '>'
{
last = middle - 1;
}

关于c - C中数组的冒泡排序和二分查找的组合代码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61896041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com