【问题标题】:Binary search with bubble sort冒泡排序的二分查找
【发布时间】:2013-04-04 20:17:14
【问题描述】:

是否可以进行使用冒泡排序的二分搜索?

这是我的冒泡排序和二分搜索。如何组合它们?

int Search_for_Client (int cList[], int low, int high, int target) {
    int middle;
    while (low <= high) {
        middle = low + (high - low)/2;
        if (target < cList[middle])
            high = middle - 1;
        else if (target > cList[middle])
            low = middle + 1;
        else
            return middle;
    }
    return -1;
}

int bubbleSort(char cList[], int size) {
    int swapped;
    int p;
    for (p = 1; p < size; p++) {
        swapped = 0;    /* this is to check if the array is already sorted */
        int j;
        for (j = 0; j < size - p; j++) {
            if (cList[j] > cList[j+1]) {
                int temp = cList[j];
                cList[j] = cList[j+1];
                cList[j+1] = temp;
                swapped = 1;
            }
        }
        if (!swapped)
        {
            break; /*if it is sorted then stop*/
        }
    }
}

【问题讨论】:

  • 使用冒泡排序的线性搜索到底是什么意思?你是说二分查找吗?
  • 基本上我需要结合冒泡排序和线性搜索
  • 将它们组合成什么?
  • 这不是线性搜索;这是一个二分搜索。
  • 我就是这个意思,对不起

标签: c binary-search bubble-sort


【解决方案1】:

首先,修复您的代码以使其能够编译。例如,bubbleSort 被声明为返回 int,但您不返回任何内容。

然后做这样的事情:

#include <stdio.h>

// *** paste your code here

int main(int argc, char *argv[])
{
    char data[11] = { 'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p' };
    int foundIt;

    bubbleSort(data, 11);
    foundIt = Search_for_Client(data, 0, 10, 'w');
    if (foundIt >= 0)
       printf("Found 'w' at index %d\n", foundIt);
    else
       printf("Did not find 'w'\n");
}

【讨论】:

  • 好的,所以我为它们每个都有一个模块,然后在 main 中调用它们?
  • 不确定为他们提供模块是什么意思。你的意思是一个DLL?如果是这样,那很好,但它可能比你现在需要的更复杂。最简单的方法是将您拥有的代码粘贴到我的示例中。在main 之前粘贴您的代码。这样你就有了一个可以自己编译和运行的简单文件。
  • 好的,但这是一个较大程序的一部分,因此更改 [main] 会弄乱整个程序。不过我会试试这个。谢谢。
【解决方案2】:

是的,您可以使用冒泡排序对数组进行排序,然后对结果排序后的数组使用二分查找。

然而,值得注意的是,还有比冒泡排序更有效的排序方法。

【讨论】:

    猜你喜欢
    • 2013-04-23
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 2013-10-09
    • 2018-02-08
    相关资源
    最近更新 更多