c - 冒泡排序的二分查找

标签 c binary-search bubble-sort

是否可以使用冒泡排序进行二分查找?

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

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*/
        }
    }
}

最佳答案

首先,修复您的代码以便其可以编译。例如,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");
}

关于c - 冒泡排序的二分查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15820907/

相关文章:

用 C 调用 Lua 字符串

c - 尝试将数字从 .txt 写入二进制文件

c++ - 二进制搜索插入字符字符串。错误在哪里?

c - 精炼拼写检查 C 程序

c - 冒泡排序问题

c++ - 预处理后解析 C++ 源文件

c - 在字符串中存储 double 值。C

go - 高效二分查找 []byte 而不是 [][]byte

c++ - 按 Alpha 顺序对 2D 字符数组进行排序?

java - 为冒泡排序执行计时