是否有可能使用冒泡排序对它进行二进制搜索?
这是我的气泡排序和二进制搜索。如何合并它们?
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/