I am working on a problem when I am given a sorted array of integers, and I have to take the data from the user, find the input and return the first instance of this input (if it exists) and the number of times it appears.
I wrote a program with the following approach: I take input from the user. Then I use binary search to find the value. If it exists, I save the index as m . After that, I write two while . The first cycle checks the number of occurrences of the value to the left, and the second does the same, but to the right. For example, a binary search may search for 5, and it finds it. However, he lands on the third, i.e. {.....5,5,**5**,5....} . The first while will count two on the left, and the second, while the loop will count one on the right. Then I summarize them and return the total number of instances. If the input value does not exist, I skip the above code and just return -1.
In the body of the main function, I check the return value. If it is -1, I tell the user that the value was not found. If the return value => 0, I print the required information.
In any case, I wrote C code for the program, but I can not get it to work correctly. I get seg. error error, I donโt know what I am doing wrong though. In any case, any help would be appreciated. For a while I banged my head about this problem. It was interesting and difficult, and I think I have the right logic; but I can't get it to work correctly. Anyway, here is the code:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> /* function prototype */ int get_num_of_ints( const int* arr, size_t r, int N, size_t* f, size_t* count ); int main() { int i; int N; /* input variable */ int arr[]={1,1,2,3,4,4,4,4,5,5,6,7,7,7,7,8,9,9}; /* array of sorted integers */ size_t r = sizeof(arr[i])/sizeof(int); /* right bound */ size_t f; /* first match index */ size_t *fPtr; fPtr = &f; size_t count; /* total number of matches */ size_t *countPtr; countPtr = &count; printf( "\nPlease input the integer you would like to find.\n" ); scanf( "%d", &N ); int a = get_num_of_ints( arr, r, N, fPtr, countPtr ); if( a == -1) printf( "%d has not been found.\n", N ); else if(a >= 0){ printf( "The first index is %d.\n", f ); printf( "The total number of values is %d.\n", count ); } return 0; } /* function definition */ int get_num_of_ints( const int* arr, size_t r, int N, size_t* f, size_t* count ) { int l = 0; int m; int w=r; size_t *fPtr; size_t *countPtr; while(l <= r){ m = l +(r - l)/2; if(arr[m] < N) l = m+1; else if(arr[m] > N) r = m-1; else if(arr[m]==N) m=m; break; } if( l > r) m = -1; if( m >= 0 ){ int j = m-1; int L = 0; while(arr[j] == arr[m] && j >= 0){ L++; j--; } if( j>= 0 && L > 0 ) *fPtr=j; else *fPtr=m; int h = m + 1; int R = 0; while( arr[h]==arr[m] && h <= w ){ R++; h++; } *countPtr = (R + L + 1); return *fPtr; } else if( m==-1) return -1; }