can not pass all the test cases - c

problem:
Write a C program to implement Binary Search Algorithm.
Include a function
int BinarySearch (int, int, int *, int x) --- The 1st parameter is the lower limit of the list or array, the 2nd parameter is the upper limit of the list or array, the third parameter is a pointer to the array and the fourth parameter is the search element.
Please note that the index of the search element is returned by the function. If the search element is not present in the array, -1 is returned.
Assume that the maximum size of the array is 10 . Please note that if a is the array, then a[0] is in position 0, a[1] is in position 1 ...
I tried this ,but it's test cases passes says only 75%,and it can't find the element if n=1;Thanks in advance :)
#include<stdio.h>
int BinarySearch(int, int ,int *, int);
int main(){
int first=0, last;
int a[20],search,s=0,n,i;
//int j,temp=0;
printf("Enter the number of elements :\n");
scanf("%d",&n);
printf("Enter the elements :\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searched :\n");
scanf("%d",&search);
last=n-1;
s=BinarySearch(first, last, a, search);
if(s>0){
printf("The element %d is in position %d",search,s);
}
else{
printf("The element %d is not present in the array",search);
}
return 0;
}
int BinarySearch(int l, int h, int *a, int x)
{
int mid;
while(l<=h){
mid=(l+h)/2;
if (x==a[mid])
return mid;
else if(x<a[mid])
h=mid-1;
else if(x>a[mid])
l=mid+1;
}
return -1;
}

Related

Why is only the first element of the output wrong?

I have recently started practicing on C. The output is reversed except for first element. Can anyone tell me what is wrong here?
I also tried using for loop but that is displaying the array as it is.
#include<stdio.h>
#include<conio.h>
int main()
{
int temp;
int i,n;
printf("Enter value of n:");
scanf("%d",&n);
int array1[n];
int k=0,j=n;
printf("Enter the five numbers\n");
for(i=0;i<n;i++)
{
printf("Enter the number %d:",i+1);
scanf("%d",&array1[i]);
}
printf("The array is:\n");
for(i=0;i<n;i++)
{
printf("%d ",array1[i]);
}
while(k<j)
{
temp=array1[k];
array1[k]=array1[j];
array1[j]=temp;
j--;
k++;
}
printf("\nThe array after reversing is:\n");
for(i=0;i<n;i++)
{
printf("%d ",array1[i]);
}
}
You are assigning array1[k] to array1[j] and you initialized j to n, so it swaps the value in array1[k] with array1[j] => in the first iteration, the value j = n, however the index of the final element is n-1. (indexes are 0,1,2,3,4,...n-1). So it tries to get the value of position n, where there is actually no value stored ( it is outside the array ). Change j to n-1 in int k=0,j=n;

Program to check if a given number is present in an array having all numbers in ascending order

The following C program works fine but not for the values which are at zeroeth position or smaller than the value at zeroeth position. This program basically takes a value and checks if the given value is in the array or not.It first compares the given value with the middle value of the array and determines if it matches it or is in the upper half or lower half and then proceeds into the selected half and proceeds in a similar way there as well until it gets the value or if the range comes out to be zero. But here it shows no result just a blinking cursor on screen(in case of value at zeroeth position or a value smaller than that).
#include<stdio.h>
main()
{
int n, x,b;
int s[]= {2,3,7,9,33,58};
n=6;
printf("Enter the number which we want to find in the array ");
scanf("%d",&x);
b=binsearch(n, s, x);
printf("The position is: %d",b);
}
int binsearch(int n, int v[], int x)
{
int low, high, mid;
low=0;
high= n-1;
while(low<=high)
{
mid=(low+high)/2;
if (x<v[mid])
high=mid+1;
else if (x>v[mid])
low=mid+1;
else
return mid;
}
return -1;
}
If we make following changes then the program gives the same problem but for value at last position or larger.
#include<stdio.h>
main()
{
int n, x,b;
int s[]= {2,3,7,9,33,58};
n=6;
printf("Enter the number which we want to find in the array ");
scanf("%d",&x);
b=binsearch(n, s, x);
printf("The position is: %d",b);
}
int binsearch(int n, int v[], int x)
{
int low, high, mid;
low=0;
high= n-1;
while(low<high)
{
mid=(low+high)/2;
if (x<v[mid])
high=mid;
else if (x>v[mid])
low=mid;
else
return mid;
}
return -1;
}
It would be better to modify your binary search function to take low and high as parameters instead of n.
int binsearch(int v[], int low, int high, int x)
{
int mid=(low+high)/2;
if(low<=high)
{
if (x<v[mid])
high=mid-1;
else if (x>v[mid])
low=mid+1;
else
return mid;
return binsearch(v, low, high, x);
}
return -1;
}
If x is equal to v[mid], mid is returned.
If x is lower than the middle value, high is made mid-1 and if x is higher than the middle value, low is made mid+1 thereby leaving one half of the part of array currenlty under consideration.
binsearch() is a recursive function which keep getting called till low>high.
The function would return the position if a match is found and otherwise -1 is returned.

C - Longest subarray of specified elements from given array

I need help with the following problem:
Given an array arr of structs
typedef struct
{
char name[20];
float amount,price;
}product;
Print the longest subarray of elements from array arr such that the arr element has greater or equal price than some value which is read.
Function to check if element has greater or equal price than a value is given as an argument of a function void subarray(product *arr,int n,int (*check)(product * ,float ),
product *newArr,int *len_newArr,float value)
where newArr is the output subarray.
Here is my code:
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
char name[20];
float amount,price;
}product;
void subarray(product *arr,int n,int (*check)(product * ,float ),
product *newArr,int *len_newArr,float value)
{
len_newArr=0;
int *current_len;
current_len=0;
int i;
for(i=0;i<n;i++)
{
//if condition is true, increment current length of newArr
//and store that element to newArr
if((*check)(arr+i,value))
{
current_len++;
newArr[i]=arr[i];
}
else
//begin with the next subarray
current_len=1;
//update newArr length
if(current_len > len_newArr)
len_newArr=current_len;
}
newArr=calloc(*len_newArr , sizeof(product));
//print the subarray
for(i=0;i<len_newArr;i++)
printf("%-19s %6.2f %6.2f\n",newArr[i].name,newArr[i].amount,newArr[i].price);
}
int check(product *pr,float value)
{
if(pr->price >= value)
return 1;
return 0;
}
void inputProduct(product *pr)
{
printf("name: ");
scanf("%s",pr->name);
printf("amount: ");
scanf("%f",&pr->amount);
printf("price: ");
scanf("%f",&pr->price);
}
int main()
{
int n,i;
product *arr,*newArr;
int len_newArr;
float value;
do
{
printf("n = ");
scanf("%d",&n);
}
while(n<1);
arr=malloc(n * sizeof(product));
newArr=calloc(n,sizeof(product));
for(i=0;i<n;i++)
{
printf("%d. product: \n",i+1);
inputProduct(arr+i);
}
printf("value: ");
scanf("%f",&value);
subarray(arr,n,&check,newArr,&len_newArr,value);
return 0;
}
The program gives warnings assignment makes pointer from integer without a cast at line
//begin with the next subarray
current_len=1;
and comparison between pointer and integer at line
//print the subarray
for(i=0;i<len_newArr;i++)
printf("%-19s %6.2f %6.2f\n",newArr[i].name,newArr[i].amount,newArr[i].price);
int *current_len=0; /* assigining NULL to a pointer to int */
This
*current_len++;
Is equivalent to *NULL++ and you can not dereference a pointer to NULL. [More info]
Same here:
*current_len=1;
It seems that you want a plain int instead of a pointer to int

C Searching A Value In Manually Filled Array

I'm trying to write a program which includes an array that filled by user and find a value in it which specified by user then print if it found and count of that number in array.But it works only for first element of array.My code is below:
`void searchh(int arr[],int search,int number,int counter);
int main()
{
int number,search,i;
int counter=0;
printf("How many numbers will you enter?");
scanf("%d",&number);
int array[number];
for(i=0;i<number;i++){
printf("Please enter the %d. element of the array:",i+1);
scanf("%d",&array[i]);
}
printf("Please enter the number that you're looking for:");
scanf("%d",&search);
searchh(array,search,number,counter);
return 0;
}
void searchh(int arr[],int search,int number,int counter){
int i,c;
int key=search;
int num=number;
counter=0;
int arrsize=(int)(sizeof(arr)/sizeof(int));
int arrayent[(int)(sizeof(num)/sizeof(int))];
for(i=0;i<arrsize;i++)
{
if(arr[i]==key)
{
arrayent[counter]=i;
counter++;
}
}
printf("The number that you're looking for which is %d is found %d times.\nLocations:",key,counter);
if(counter>0){
for(c=0;c<sizeof(arrayent)/sizeof(int);c++){
printf("%d\n",arrayent[c]);
}
}
else
printf("Number doesn't exist!!");
}`
And Outputs:
Thanks for your helps.
int arrsize=(int)(sizeof(arr)/sizeof(int));
This already doesn't do what you think it does. sizeof(arr) - could be 4 if size of pointer is 4 bytes. In other words you can't check array size like that inside function, arr decays to pointer of first element of array. Hence sizeof(arr) will return size of pointer which could be 4 or 8. You need to pass the number of elements of the array to the function as parameter - which is number in your case.
This:
int arrayent[(int)(sizeof(num)/sizeof(int))];
is also strange. num is int. sizeof(num) and sizeof(int) will be same - and division will give you 1.
IMO these two lines
int arrsize=(int)(sizeof(arr)/sizeof(int));
int arrayent[(int)(sizeof(num)/sizeof(int))];
should just go as
int arrsize = number;
int arrayent[number];
PS. Also try to use a debugger to help you with some kind of issues.

Error in Bubble sort. Getting an input wrong

I have the following source and when I execute it the values are getting their signs changed. I am not able to find out where I am going wrong. Any suggestions is helpful
Code
#include <stdio.h>
#include <stdlib.h>
int arrsort(int *arr, int size);
int display(int *arr, int size);
int main()
{
int s_o_1=0, s_o_2=0;
int i; //index for arrays
int a[s_o_1],b[s_o_2];
printf("enter the size of the first array\n");
scanf("%d",&s_o_1);
printf("Enter the values of the first array\n");
for (i=0;i<s_o_1;i++)
{
scanf("%d",&a[i]);
}
printf("enter the size of the second array\n");
scanf("%d",&s_o_2);
printf("Enter the values of the second array\n");
for (i=0;i<s_o_2;i++)
{
scanf("%d",&b[i]);
}
//sort the first array
arrsort(a,s_o_1);
printf("The sorted first array is\n");
display(a,s_o_1);
//sort the second array
arrsort(b,s_o_2);
printf("The sorted second array is\n");
display(b,s_o_2);
}
int arrsort(int *arr, int size)
{
int temp; //for holding the temp value
int i; //for indexing
int j;
for(j=0;j<size;j++)
{
for(i=0;i<size;i++)
{
if(arr[i]>arr[i+1])
{
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
}
int display(int *arr, int size)
{
int i; //array index
for (i=0;i<size;i++)
{
printf("%d\t",i);
}
printf("\n");
for (i=0;i<size;i++)
{
printf("%d\t",arr[i]);
}
printf("\n");
}
Output
enter the size of the first array
5
Enter the values of the first array
1 5 -10 -15 3
enter the size of the second array
5
Enter the values of the second array
-3 -5 15 9 10
The sorted first array is
0 1 2 3 4
-15 -10 3 5 10
The sorted second array is
0 1 2 3 4
-15 -10 -5 -3 9
The problem is the array declaration:
int s_o_1=0, s_o_2=0;
int i; //index for arrays
int a[s_o_1],b[s_o_2];
The arrays are probably declared with size 0. Either declare with an appropriate maximum size, or declare after reading the sizes for the arrays.
Your code has undefined behaviour. In this line:
int a[s_o_1],b[s_o_2];
It declares arrays with zero size. When later get values for s_o_1 and s_o_2 the array size won't change. So all your reads & writes lead to undefined behaviour.
C standard requires array should be of non-zero length.
The way you reserve memory is not correct int a[s_o_1],b[s_o_2];
You must use int *a, *b; and later after scanf("%d",&s_o_1); you need to do something like a = (int*)malloc(sizeof(int)*s_o_1);
The same goes to allocating memory for b.
Also bubble sort alghorithm should be something like bellow
for(j=0;j<size - 1;j++)
{
for(i=j + 1;i<size;i++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}

Resources