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

标签 c arrays sorting binary-search bubble-sort

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

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

#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/

相关文章:

c - "Must use ' 结构 ' tag to refer to type ' 节点 '"

c - 如何将结构写入文件?

c - 16 位位域导致*从未初始化的内存中读取*警告

php - JSON 数组到 PHP 日期时间

java - 我应该使用 java 中的哪个集合进行排序以获得更高的性能?

c - 使用 strtok 时预期的不合格 ID

c++ - 关于编译时 1.constructor 和 2.array 定义的一些疑问

ios - 在for循环后按值对字典数组进行排序?

list - 当对象是动态的时,如何在 Scala 中对列表进行排序?

python - 以递归方式对Python列表进行排序