Practical 8 by Karan

 #include <stdio.h>

struct emp {

int no;

int sal;

char name[20];


};

 

int binarySearch(struct emp a[], int n, int x)

{

   

   int low=0, mid, high=n-1, count = 0;

   while(low <= high)

   {

       count++;

        mid = (low + high) / 2;

        if (x < a[mid].no)

            high = mid - 1;

        else if (x > a[mid].no)

         low = mid + 1;

       else {

        printf("no of search = %d\n",count);

      return mid;

       }

   }

return -1;



}

 

 void printArray(struct emp array[], int size) {

  for (int i = 0; i < size; ++i) {

     printf("name = %s\n",array[i].name);

    printf(" salary = %d\n ", array[i].sal);

     printf(" number = %d\n ", array[i].no);

    

  }

  printf("\n");

}



int main()

{

    int no , i,x ;

  printf("enter no of studets\n");

  scanf("%d", &no);



  struct emp data[no] ;


  for(i=0;i<no;i++){   

    printf("\nEnter Name of student %d:", (i+1));    

scanf("%s",&data[i].name);


printf("Enter number:");    

scanf("%d",&data[i].no);    

 

printf("Enter salary:");    

scanf("%d",&data[i].sal);    

}    

 printArray(data, no);

 printf("enter no to be searched \n");

 scanf("%d",&x);


    int result = binarySearch(data, no , x);

    if(result == -1)

         printf("Element is not present in array");

         else 

          printf("Employee is found at index %d", result);

    return 0;

}

Comments

Popular posts from this blog

DAA P4 bfs, dfs

DAA P8 graph coloring