Pages

Visitors

Thursday 5 January 2012

Binary Search


#include <stdio.h>

main()

{
    int a[30],n,i,t,low,mid,high,found = 0;

    printf("\n enter the number of elements in array");

    scanf("%d",&n);

    if(n>30)

    {
        printf("\n too many numbers");
        exit(0);
    }

printf("\n enter elements of array: ");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

printf("\n enter element to search: ");

scanf("%d",&t);

low = 0;

high = n-1;

while (high >= low)

{
    mid = (low+high)/2;

    if (a[mid] == t)
    {
        found = 1; break;
    }

    else if (t<a[mid])

             high = mid-1;

             else low = mid + 1;
}

if (found ==0)

printf("\n not found");

else printf("\n found at %d",mid);

getch();
}

Bubble Sort


#include <stdio.h>

main()

{
     int a[30],n,i,j,temp;

     printf("\n how many numbers");

     scanf("%d",&n);

     if (n>30)

     {
         printf("\n too many numbers");


     }

     printf("\n enter the array elements: ");

     for (i=0;i<n;i++)
     scanf("%d",&a[i]);

     for (i=0;i<n-1;i++)

     for(j=0;j<(n-i)-1;j++)

     if (a[j]>a[j+1])

     {
         temp = a[j];

         a[j] = a[j+1];
         a[j+1] = temp;
     }

     printf("The numbers in sorted order are : \n");

     for(i=0;i<n;++i)

     printf("\n%d",a[i]);

     getch();
}