Is it possible to have a binary search that uses a bubble sort to sort it?
This is my bubble sort and binary search. How do I combine them?
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*/
}
}
}
First, fix your code so it compiles. For example, bubbleSort
is declared as returning int but you don't return anything.
Then do something like this:
#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");
}