Okay, here is my code. Unfortunately I get a seg fault on line 50 where this comparison is made for inputs less than or equal to zero:
And here is my code:
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)/sizeof(arr[0]) - 1; /* right bound */
size_t f; /* first match index */
size_t count; /* total number of matches */
printf( "\nPlease input the integer you would like to find.\n" );
scanf( "%d", &N );
int a = get_num_of_ints( arr, r, N, &f, &count );
if( a == -1)
printf( "%d has not been found.\n", N );
else if(a >= 0){
printf( "The first match index is %d.\n", f );
printf( "The total number of instances 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;
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;
printf( "M is %d\n", m );
if( m >= 0 ){
int j = m-1;
int L = 0;
while( j >= 0 && arr[j] == arr[m] ){
L++;
j--;
}
printf( "J is %d\n", j );
if( j> 0 && L > 0 )
*f=j+1;
else if( j <= 0 )
*f=0;
else if( L==0 )
*f=m;
int h = m + 1;
int R = 0;
while( arr[h]==arr[m] && h <= w ){
R++;
h++;
}
printf( "L is %d and R is %d.\n", L, R );
*count = (R + L + 1);
return *f;
}
else if( m==-1)
return -1;
}
I dont' see why the comparison should matter or cause problems.