How to dynamically allocate array in c ? Search element using binary search
To dynamically allocate array in c we can use malloc() or calloc() functions.What is the working of these functions illustrated below.
malloc():
malloc() is used to dynamically allocate array in c in which will give the size how much we want to allocate and can cast to any data type.In malloc() all the memory is uninitialized.
Syntax of malloc():
ptr=(cast_type*)malloc(size);
where,ptr is a pointer of type of array you want
size is how much size of memory you want
For ex:
int *ptr;
ptr=(int*)malloc(40*sizeof(int));
This will create 80 bytes of integer type because integer is of 2 bytes.
calloc():
calloc() is also used for dynamically allocate array in c in which memory is initialized to zero.We have to specify how many blocks we want to allocate.
Syntax of calloc():
ptr=(cast_type*)calloc(n,size);
where,ptr is a pointer of type of array you want
n is how many blocks
size is how much size of memory you want
For ex:
int *ptr;
ptr=(int*)calloc(25,sizeof(int));
This will create integer type array of 25 blocks of 2 bytes each all initialized to zero.
Search element using binary search:
Binary Search:We will first sort the array in ascending order.Then divide the array in two halves and find the middle element by using (last_index-first_index)/2,if searching element is equal to searching element then return that element else if greater than middle then will go to the second half else go to first half.This process goes on until we find our searching element.
For Ex:
Assume array is sorted.
Program to dynamically allocate array in c and search element using binary search
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,*ptr,mid,last,first,searching_element;
printf("Enter how many elements you want");
scanf("%d",&n); //taking input
ptr=(int*)malloc(n*sizeof(int)); //dynamically allocating array
for(int i=0;i<n;i++)
{
scanf("%d",ptr+i); //taking inputs in ascending order in array
}
printf("Enter Searching element");
scanf("%d",&searching_element); //taking input of searchelement
last=n-1;
first=0;
while(1)
{
mid=(last-first)/2;
if(ptr[mid]==searching_element)
{
printf("Element fount at : %d",mid+1);
break;
}
else if(searching_element>ptr[mid])
{
first=mid+1;
}
else
{
last=mid-1;
}
}
}
So this is the explanation to dynamically allocate array in c and finding element using binary search.
Comments
Post a Comment