Have a Read!

Hi Everyone.
The idea for this page is to provide new c users simple c tutorials to learn how to develop the logic and more importantly correct way to write syntax.
ENJOY !!!

Sunday, February 6, 2011

C Program for Searching and Sorting Data

#include<stdio.h>
#include<stdlib.h>
void sorter(int b[],int size);
void searcher(int b[],int size);
int main()
{
    int a[40],i;
    printf("\n\n\nTHE DATA SET CONTAINS 40 VALUES WHICH ARE AS FOLLOW:");
    printf("\n");
    for(i=0;i<40;i++)
    {a[i]=rand()%40;
    printf("%d ",a[i]);
    }
    sorter(a,40);
    searcher(a,40);
    return 0;
}
void sorter(int b[],int size)
{
    int i,j,k,temp;
    for(i=0;i<size;i++)
        {
        for(j=0;j<size-1;j++)
        {
            if(b[j]>b[j+1])
            {temp=b[j];
                 b[j]=b[j+1];
                 b[j+1]=temp;
            }
         }
        }
    printf("\n\n\nTHE DATA IS BEING SORTED AS FOLLOW:\n");
    for(k=0;k<40;k++)
    {printf("%d ",b[k]);}
    printf("\n\n");
    }
void searcher(int b[],int size)
{
    int key,found,low,mid,high;
    printf("\nWhat value you want to locate=");
    scanf("%d",&key);
    low=0;
    high=size-1;
    while(low<=high)
    {   
    mid=(low+high)/2;
    if(b[mid]==key)
    {
    found=1;
    break;
    }
    else if(b[mid]>key)
    {
    high=mid-1;
    }
    else
    {
    low=mid+1;
    }
    }
    if(found==1)
    printf("%d is in the data set\n",key);
    else printf("%d is not in the data set\n",key);
}

No comments:

Post a Comment

Related Posts with Thumbnails