I wrote a function in C that searches for an element k
in an array arr
(its sorted, all its elements are in descending order):
int search(int arr[], int start, int end, int k) {
int mid = 0.5 * (start end);
if (k == arr[mid] || k == arr[start] || k == arr[end]) {
return 1;
} else
if (k > arr[mid]) {
end = mid;
search(arr, start, end, k);
} else {
start = mid;
search(arr, start, end, k);
}
}
int main() {
int n, i, k;
scanf("%d", &n);
int arr[n];
for (i = 0; i < n; i )
scanf("%d", &arr[i]);
scanf("%d", &k);
if (search(arr, 0, n - 1, k) == 1)
printf("1");
else
printf("0");
}
I want to make this return 0 whenever the element k
does not exist in the array. I tried to add a return 0
way at the bottom of the function. But my printf
function then doesn't print 0. It does print 1 however. Can anyone help me understand what's going on here?
CodePudding user response:
First, please make sure that the array is sorted. Second is you need to return the value from the subsequent calls you are making. Third is you need to take care of the range of search being done to actually bisect them and individually search in each half.
Fixed Snippet:
#include <stdio.h>
int search(int arr[], int start, int end, int k) {
if(start > end) return 0;
int mid = 0.5 * (start end);
if (k == arr[mid]) return 1;
else if (k > arr[mid]) return search(arr, start, mid - 1, k);
return search(arr, mid 1, end, k);
}
int compare( const void* a, const void* b)
{
int int_a = * ( (int*) a );
int int_b = * ( (int*) b );
if ( int_a == int_b ) return 0;
else if ( int_a < int_b ) return 1;
else return -1;
}
int main() {
int n, i, k;
scanf("%d", &n);
int arr[n];
for (i = 0; i < n; i )
scanf("%d", &arr[i]);
scanf("%d", &k);
// sort them to apply binary search unless you wish to insert only sorted values
qsort( arr, n, sizeof(int), compare );
if (search(arr, 0, n - 1, k) == 1)
printf("1");
else
printf("0");
}