I am using binary search algorithm to find a number in a predefined array, but if i am entering the value already in an array i am getting correct answer, but on entering a value not in an array like 101,100,121 i am just getting number 10 as output
#include <stdio.h>
int binarysearch(int A[],int key);
int main()
{
int key,answer;
int A[10]={0,5,8,10,12,14,15,18,19,21};
scanf("%d",&key);
answer=binarysearch(A,key);
if (answer!=-1)
{
printf("%d",answer);
}
else
{
puts("NOT FOUND");
}
}
int binarysearch(int A[],int key)
{
int i;
int h,l,m;
h=10;
l=0;
while(l<=h)
{
m=(h+l)/2;
if(A[m]==key)
{
return m;
}
else if(key<A[m])
{
h=m-1;
}
else
{
l=m+1;
}
}
return -1;
}
Change the condition
while(l<=h)
to
while ( l < h )
And change this code snippet
else if(key<A[m])
{
h=m-1;
}
the following way
else if(key<A[m])
{
h = m;
}
The function could be defined like
int binarysearch( const int A[], int n, int key )
{
int l = 0;
int h = n;
while ( l < h )
{
int m = ( h + l ) / 2;
if ( A[m] == key )
{
return m;
}
else if( key < A[m] )
{
h = m;
}
else
{
l = m + 1;
}
}
return -1;
}
And called like
answer=binarysearch( A, 10, key );
Related
#include <stdio.h>
int bsearch(int ar[],int n,int key)
{
int s=0;
int e=n-1;
while(s<=e){
int mid=(e+s)/2;
if(mid==key){
return mid;
}
else if(key<mid){
e=mid-1;
}
else if(key>mid){
s=mid+1;
}
}
return -1;
}
I made the function for the binary search
int main()
{
int n,key;
int ar[n];
scanf("%d",&n);
for(int i=0;i<n;i++){
printf("ar[%d]= ",i);
scanf("%d",&ar[i]);
}
printf("Enter key>> \n");
scanf("%d",&key);
printf("%d is the index",bsearch(ar,n,key));
return 0;
}
Then I inputted an sorted array but with repetitions. Shown in the following image.
The output is coming as 3 is the index.
But it should as come as 6 is the index.
mid is an index of element, not a value. So, I have corrected your function:
#include <stdio.h>
int bsearch(int ar[], int n, int key)
{
int s=0;
int e=n-1;
while(s <= e){
int mid = (e + s) / 2;
if(key == ar[mid]) {
return mid;
}
else if(key < ar[mid]) {
e = mid-1;
}
else if(key > ar[mid]) {
s = mid+1;
}
}
return -1;
}
I've got an assignment in which functions return MIN and MAX value of elements in an array. But I also have to return value from function with 'NULL' parameter and I don't understand it.
My code:
int array_min(const int [], const int);
int array_max(const int [], const int);
int main() {
int input_arr[] = {2,3,4,5,6};
printf("%d\t", array_min(input_arr, 5));
// : 2
printf("%d\t", array_max(input_arr, 5));
// : 6
printf("%d\t", array_max(NULL, 5));
// : -1
return 0;
}
int array_min(const int input_arr[], const int arr_size) {
int a, b = arr_size, min = input_arr[0];
for(a = 0; a < b; a++) {
if(input_arr[a] < min) {
min = input_arr[a];
}
}
return min;
}
int array_max(const int input_arr[], const int arr_size) {
int a, b = arr_size, max = input_arr[0];
for(a = 0; a < b; a++) {
if(input_arr[a] > max) {
max = input_arr[a];
}
}
return max;
}
So, my question is, how do I use 'NULL' in function to get return value -1?
It is modified version of the #chux-ReinstateMonica answer with some changes.
Use size_t (not int) for sizes.
Try if possible to have one return point from the function
There is no need to check index 0 as it will be equal to the min value
In this case it is better to keep value and the index of the minimal value instead of pointer to it (it will help the compiler to optimize the code)
const int *array_min1(const size_t arr_size, const int input_arr[arr_size]) {
const int *result = arr_size ? input_arr : NULL;
if (result)
{
size_t a, min_index = 0;
int min = input_arr[0];
for(a = 1; a < arr_size; a++) {
if(input_arr[a] < min) {
min = input_arr[a];
min_index = a;
}
}
result = input_arr + min_index;
}
return result;
}
how do I use 'NULL' in function to get return value -1?
Parameter input validation is a common task. Simple test up front.
When input is troublesome:
int array_min(const int input_arr[], const int arr_size) {
if (input_arr == NULL || arr_size <= 0) {
return -1;
}
...
Returning -1 on error is a weak design choice as it is not distinguishable from a good return of -1:
int input_arr[] = {-1, 2, 3, 4, 5};
printf("%d\t", array_min(input_arr, 5));
functions return MIN and MAX value of elements in an array.
Consider instead: return the address of the minimum/maximum. Return NULL on error.
// int array_min(const int input_arr[], const int arr_size) {
const int *array_min(const int input_arr[], const int arr_size) {
if (input_arr == NULL || arr_size <= 0) {
return NULL;
}
//int a, b = arr_size, min = input_arr[0];
int a, b = arr_size;
const char *min = &input_arr[0];
// for(a = 0; a < b; a++) {
for(a = 1; a < b; a++) { // No need to test input_arr[0]
//if(input_arr[a] < min) {
if(input_arr[a] < *min) {
//min = input_arr[a];
min = &input_arr[a];
}
}
return min;
}
Now the calling code can detect troubles.
// printf("%d\t", array_min(input_arr, 5));
const int *min = array_min(input_arr, 5);
// or
const int *min = array_min(input_arr, 0);
// or
const int *min = array_min(NULL, 5);
if (min) {
printf("%d\t", *min);
} else {
printf("Min not found\t");
}
I saw a problem on the web,i.e, I am trying to sort a stack using another reference stack in C. I tried to do it by implementing it as an array but it is not working.
(condition is that you have to use only arrays)
#include <stdio.h>
int MAXSIZE = 5;
int stack[5];
int tmpstack[5];
int tmp;
int top = -1;
int top2=-1;
int isempty(int A[],int B) {
if(B == -1)
return 1;
else
return 0;
}
int isfull(int A[],int B) {
if(B == MAXSIZE)
return 1;
else
return 0;
}
int pop(int A[],int B) {
int data;
if(!isempty(A,B)) {
data = A[B];
B = B - 1;
return data;
}
else {
printf("Could not retrieve data, Stack is empty.\n");
}
}
int push(int data,int A[],int B) {
if(!isfull(A,B)) {
B = B + 1;
A[B] = data;
}
else {
printf("Could not insert data, Stack is full.\n");
}
}
int sortStack(int stack[])
{
int tmpStack[MAXSIZE];
while (!isempty(stack,top))
{
int tmp = stack[top];
pop(stack,top);
while (!isempty(tmpstack,top2) && tmpstack[top2] > tmp)
{
push(pop(tmpstack,top2),stack,top);
}
push(tmp,tmpstack,top2);
}
return 0;
}
int main() {
int n ,a;
n=5;
for(int i = 0;i < n ; ++i){
scanf("%d",&a);
push(a,stack,top);
}
sortStack(stack);
while (!isempty(tmpstack,top2))
{
printf("%d ",tmpstack[top2]);
pop(tmpstack,top2);
}
return 0;
}
What I did here is that I made similar functions in arrays which we used in stacks only and we are supposed to use them only for implementing our stacks.
I don't understand why printq() function prints 0, but when I access it back in main() it prints. I don't understand what I am doing wrong, I tried using pointers, but I get some different error in the priority queue. I want to print elements in array pq[10].
EDIT: I realized that the elements are stored but when I use pq[R].data it prints
but when I use pq[i].data in printq() and put it inside for loop, it prints zero.
#include <stdio.h>
int F = -1, R = -1;
int item, max = 10;
struct prioq {
int data;
int prio;
};
struct prioq pq[10] = { 0 };
void printq()
{
int i = 0;
printf("%d,", pq[i].data);
printf("QUEUE :");
for (i = 0; i < max; i++) {
printf("%d,", pq[i].data);
}
printf("\n");
printf("PRIO :");
for (i = 0; i < max; i++) {
printf("%d,", pq[i].prio);
}
}
void enqueue(int item, int p, struct prioq pq[])
{
if (F == -1 && R == -1 || F > R) {
F == 0;
R == 0;
pq[R].data = item;
pq[R].prio = p;
printf("%d", pq[R].data);
printf("%d", pq[R].prio);
printq();
} else if (R == max-1 || R > max) {
printf("overflow\n");
} else if (R < max) {
R++;
pq[R].data = item;
pq[R].prio = p;
printq();
}
}
void dequeue(struct prioq pq[])
{
int large = 0;
if (F == -1) {
printf("underflow\n");
} else {
int i;
for (i = 0; i < max; i++) {
if (pq[i].prio > large) {
large = i;
}
}
}
item = pq[large].data;
pq[large].prio = 0;
pq[large].data = 0;
printf("item deleted: %d\n", item);
printq();
}
void main()
{
int item = 0;
int c = 0, p = 0;
do {
printf("choose your option\n");
printf("1.Insert, 2.Delete, 3.Exit\n" );
scanf("%d", &c);
switch (c) {
case 1:
printf("Enter the priority and element to insert\n");
scanf("%d %d", &item, &p);
enqueue(item,p,pq);
printf("%d", pq[R].data);
printf("%d", pq[R].prio);
break;
case 2:
dequeue(pq);
break;
default:
c = 3;
break;
}
} while (c != 3);
printf("exited\n");
}
In your enqueue function, change the == in the F and R assignments to =.
void enqueue(int item, int p, struct prioq pq[])
{
if (F == -1 && R == -1 || F > R) {
F = 0; // Here
R = 0; // And here
pq[R].data = item;
pq[R].prio = p;
printf("%d", pq[R].data);
printf("%d", pq[R].prio);
printq();
} else if (R == max-1 || R > max) {
printf("overflow\n");
} else if (R < max) {
R++;
pq[R].data = item;
pq[R].prio = p;
printq();
}
}
This is my solution for the Credit problem on CS50's Pset1. It involves using Luhn's Algorithm to test the validity of the Credit Card Number entered and based on a few conditions attempts to identify the Credit Card Company.
Check_Length attempts to find the length of the number entered.
Check_Company attempts to ID the company.
Check_Luhn validates the number based on Luhn's Algorithm.
I'd like to know if this could be done with fewer lines of code.
#include <stdio.h>
#include <cs50.h>
#include <stdbool.h>
int check_length(long);
void check_company(int,long);
bool check_luhn(long,int);
int length;
int main(void)
{
long c = get_long("Enter Credit Card Number: ");
check_length(c);
check_luhn(c,length);
if(check_luhn(c,length)==true)
{
check_company(length,c);
}
else printf("INVALID\n");
}
int check_length(long w)
{
for(int i=12;i<16;i++)
{
long power = 1;
for (int k=1;k<i+1;k++)
{
power = power * 10;
}
int scale = w/power;
if (scale<10 && scale>0)
{
length = i+1;
}
}
return length;
}
void check_company(int x,long z)
{
if(x == 15)
{
int y = z/10000000000000; //z/10^13
if(y==34||y==37)
{
printf("AMEX\n");
}
else
{
printf("INVALID\n");
}
}
else if(x==13)
{
int y = z/100000000000; //z/10^11
if(y==4)
{
printf("VISA\n");
}
}
else if(x==16)
{
int q = z/1000000000000000;
int y = z/100000000000000;
if(y==51||y==52||y==53||y==54||y==55)
{
printf("MASTERCARD\n");
}
else
if(q==4)
{
printf("VISA\n");
}
else printf("INVALID\n");
}
else printf("INVALID\n");
}
bool check_luhn(long a,int b)
{
int f = 0;
int j=0;
for(int d=1;d<b+1;d++)
{
int e = a%10;
a = a/10;
if(d%2==1)
{
f = f+e;
}
else
{
int m = 2*e;
int g = m%10;
int h = m/10;
j = j+g+h;
}
}
int l = j + f;
if(l%10==0)
{
return true;
}
else return false;
}