1: #include<stdio.h>
2: #include<conio.h>
3: void main()
4: {
5: int a[20], n, x, i, j, temp;
6: void search(int a[20], int b, int c);
7: clrscr();
8: printf("\nEnter the no of elements : ");
9: scanf("%d",&n);
10: printf("\nEnter the elements : \n");
11: for(i=0;i<n;i++)
12: scanf("%d", &a[i]);
13: printf("\nEnter the search element : ");
14: scanf("%d", &x);
15: for(i=0;i<n-1;i++)
16: {
17: for(j=i+1;j<n;j++)
18: {
19: if(a[i]>a[j])
20: {
21: temp=a[i];
22: a[i]=a[j];
23: a[j]=temp;
24: }
25: }
26: }
27: search(a, n, x);
28: getch();
29: }
30: void search(int a[20], int b, int c)
31: {
32: int l, h, m, s=0, i, count=0;
33: l=0;
34: h=b-1;
35: clrscr();
36: while(l<=h)
37: {
38: m=(l+h)/2;
39: if(c<a[m])
40: h=m-1;
41: else
42: if(c>a[m])
43: l=m+1;
44: else
45: if(c==a[m])
46: {
47: printf("\n\t%d is found",c);
48: s=1;
49: goto end;
50: }
51: }
52: end:
53: if(s==0)
54: printf("\n\n\t%d not found", c);
55: else
56: {
57: printf("\n\n\nThe memory location of %d is\n\n ", c);
58: for(i=0;i<b;i++)
59: {
60: if(a[i]==c)
61: {
62: printf("a[%d] \t", i);
63: count++;
64: }
65: }
66: printf("\n\n\n%d is repeated for %d time(s)", c, count);
67: }
68: }
Binary Search
Subscribe to:
Posts (Atom)
No comments:
Post a Comment