Monday, February 25, 2013

Sorting and Searching Program with C/C++ Language

Sorting and Searching Program with C/C++ Language:
Problem: How to make Sorting and Searching Program.

Solution

Sorting and Searching is an important task in programming. Here we will see such a C Program. This program is used to sorting and searching a string array. Running this program we will provide names and given names are sorted and searched by the program. Programming code is given bellow→

#include<stdio.h>  
#include<conio.h>
#include<string.h>

  struct name            // Custom Data Type
  {
      char a[10];   
       
   }b [10];                 // Custom data type’s variable


  int N,i,j;
  int c=0;
  char name[10];
  printf("How many names :");
  scanf("%d",&N);  fflush(stdin);
  {
   printf("Enter %d Name :",i+1);
   gets(b[i].a);               
  }

  printf("\n\nEntered name list :");
  {
            printf("\n%s",b[i].a);
  }

  {
            for(j=i+1;j<N;j++)
            {
             if((strcmp(b[i].a,b[j].a))>0)
               char temp[10];
               strcpy( temp,b[i].a);
               strcpy(b[i].a,b[j].a);
               strcpy( b[j].a,temp);
             }
   }
  }
  printf("\n\nSorted name list :");
   {
             printf("\n%s",b[i].a);
   }



 printf("\n\nEnter name to search :");
 gets(name);
 {
   if((strcmp(b[i].a,name))==0)
   c++;
 }
 if(c==0)
 {
   printf("%s not found .",name);
 }
 else
 {
   printf("%s remains %d times .",name,c);
 }
 }

Output





Remarks

After giving  name (string) we can see the list of name and then sorted list. When we will give a name and search, we will see that name if it is in array otherwise name not found on the screen. Here strcpy ()  function is used to copy one variable’s value another variable and strcmp() function is used to compare two string. fflush(stdin) is used to flush buffer.


1 comment: