#include<stdio.h> main() { int arr[10],i,n,key,c=0; printf("Enter the size of an array: "); scanf("%d",&n); printf("Enter the elements of the array: "); for(i=0;i<=n-1;i++) { scanf("%d",&arr[i]); } printf("Enter the number to be search: "); scanf("%d",&key); for(i=0;i<=n-1;i++) { if(arr[i]==key) { c=1; break; } } if(c==0) printf("The number is not found"); else printf("The number is found"); return 0; }
New Android apps UniqueKey
Showing posts with label Searching. Show all posts
Showing posts with label Searching. Show all posts
Friday, 20 February 2015
Linear Search
Binary search
#include<stdio.h> main() { int arr[100],i,n,key,c=0,first,last,mid; printf("Enter the number of element in array : "); scanf("%d",&n); printf("Enter the elements in ascending order : "); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } printf("Enter the number to be search : "); scanf("%d",&key); first=0; last=n-1; while(first<=last) { mid=(first+last)/2; if(key==arr[mid]) { c=1; break; } else if(key<arr[mid]){ last=mid-1; } else first=mid+1; } if(c==0) printf("The number is not found."); else printf("The number is found."); return 0; }
Binary search ( Recursion )
#include<stdio.h> int binary(int [],int,int,int,int); main() { int a[50],i,n,m,first,last,c; printf("enter the number of elements\n"); scanf("%d",&n); printf("enter all elements\n"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("enter the number to be searched\n"); scanf("%d",&m); first=0; last=n-1; c=binary(a,n,m,first,last); if(c==0) printf("element NOT FOUND\n"); else printf("element found\n"); } int binary(int a[],int n,int m, int first, int last) { int mid,c=0; if(first<=last) { mid=(first+last)/2; if(m==a[mid]) { c=1; } else { if(m<a[mid]) return binary(a,n,m,first,mid-1); else return binary(a,n,m,mid+1,last); } } return c; }
Subscribe to:
Posts (Atom)