Skip to main content

PROGRAMMING FOR PROBLEM SOLVING LAB : Program 20

Write a C program that uses non recursive function to search for a Key value in a given Sorted list of integers using binary search method


ALGORITHM:


BINARY SEARCH


1. 1. Start

2. 2. Read the value of n

3. 3. for i=1 to n increment in steps of 1

Read the value of ith element into array

4. 4. Read the element(x) to be searched

5. 5. search<--binary(a,n,x)

6. 6. if search equal to 0 goto step 7 otherwise goto step 8

7. 7. print unsuccessful search

8. 8. print successful search

9. 9. stop


PROGRAM:


#include<stdio.h> 

#include<conio.h>

int BinarySearching(int arr[20], int max, int element)

{

int low = 0, high = max - 1, middle; 

while(low <= high)

{

middle = (low + high) / 2; 

if(element > arr[middle]) 

low = middle + 1;

else if(element < arr[middle]) 

high = middle - 1;

 else

return middle;

}

return -1;

}


void main()

{

int i,j,element,temp,n, arr[50], position; 

//clrscr();

printf("\n Enter the N vaule of an array:"); 

scanf("%d", &n);

printf("\n Enter %d Elements in Array: \n",n); 

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

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

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

{

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

{

if(arr[i]>arr[j])

{

temp=arr[i]; 

arr[i]=arr[j]; 

arr[j]=temp;

}

}

}

printf("\nthe array in sorted order:-\n"); 

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

printf("%d\t",arr[i]);

printf("\n Enter Element to Search:"); 

scanf("%d", &element);

position = BinarySearching(arr,n, element); 

if(position == -1)

printf("Element %d Not Found\n", element); 

else

printf("\n Element %d Found at Position %d\n",element,position + 1); 

//getch();

}

OUTPUT:

Enter the N vaule of an array:6

Enter 6 Elements in Array: 

45 67 13 24 78 10

the array in sorted order:-

10 13 24 45 67 78

 Enter Element to Search:45

 Element 45 Found at Position 4

Comments

Popular posts from this blog

Learning and Development Interview Questions and answers for Mathematics-1.

  1). What is Mean, Mode and Median? Solution Answer: The mean is the average of a  collection of numbers or terms in a sequence. To calculate the mean use a formula is sum of total terms divided  by number of terms. The mode  is the most f requent number or term in a sequence. It means the number that occurred  highest number of times  in a sequence. To find the mode arrange the numbers in ascending or descending order and verify which number repeated most number of times in a sorted sequence. The median is the middle number/term where the sequence is arranged in ascending or descending order. If the sorted sequence have odd number of terms then  divide by 2 and round up to get the position of the median number.  If the  sorted sequence  have  even  number of terms then  divide by 2  to get the position of the median number.  2 ). What is the Difference between Fractional and Rational number? Solu...