是否可以使用冒泡排序进行二分查找?
这是我的冒泡排序和二分搜索。如何组合它们?
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/