Friday, November 21, 2014

C binary search pro



C Program to Implement Insertion Sort in C Programming


#include
#include
int main()
{
   int i, j, num, temp, arr[20];
   printf("Enter total elements: ");
   scanf("%d", &num); 
   printf("Enter %d elements: ", num);
   for (i = 0; i < num; i++)
   {
      scanf("%d", &arr[i]);
    }
   for (i = 1; i < num; i++)
   {
      temp = arr[i];
      j = i - 1;
      while ((temp < arr[j]) && (j >= 0))
      {
         arr[j + 1] = arr[j];
         j = j - 1;
      }
      arr[j + 1] = temp;
   }
   printf("After Sorting: ");
   for (i = 0; i < num; i++)
   {
      printf("%d", arr[i]);
   } 
   return 0;
}

Output

Enter total elements: 5
Enter 5 elements: 9 4 1 0 2
After sorting:  0 1 2 4 9

C Program to print Fibonacci Series using recursion

#include
#include 
int size;
int fibonacci(int prev_number, int number);
void main()
{
   static int prev_number = 0, number = 1;
   clrscr();
   printf("Enter the Size of Series (< 20) : ");
   scanf("%d", &size); 
   printf("1 ");
   fibonacci(prev_number, number);
   getch();
}

int fibonacci(int prev_number, int number)
{
   static int i = 1;
   int next_num; 
   if (i == size)
      return (0);
   else
      {
      next_num = prev_number + number;
      prev_number = number;
      number = next_num;
      printf("%d ", next_num);
      i++;
      fibonacci(prev_number, number);
   }
   return (0);
}

Output

Enter the Size of Series (< 20) : 6
1 1 2 3 5 8 13

C Program to perform binary search on array using recursion

#include
#include
#include
int binsearch(int[],int,int,int);
int main()
{
int num,I,key,position;
int low,high,list[size];
printf("\nEnter the total number of elements ");
scanf("%d",&num);
printf("\n Enter the elements of list: ");
for(i=0;i
{
scanf("%d",&list[i]);
}
low=0;
high=num-1;
printf("\n Enter element to be searched: ");
scanf("%d",&key);
position=binesearch(list,key,low,high);
if(position!=-1)
{
Printf("\n Number present at %d",(position+1));
}
else
printf("\n The number is not present in th list");
return(0);
}
int binesearch(inta[],int x,int low, int high)
{
int mid;
if(low>high)
return-1;
mid=(low+high)/2;
if(x==a[mid])
{
return(mid);
}
elseif(x
{
binsearch(a,x,low,mid-1);
}
else
{
binsearch(a,x,mid+1,high);
}
}

Output

Enter the total number of elements   :5
Enter the elements of list : 11 22      33      44      55
Enter element to be searched : 33
Number present at 3

No comments:

Post a Comment