-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.cpp
More file actions
66 lines (65 loc) · 1.18 KB
/
Copy pathbinarysearch.cpp
File metadata and controls
66 lines (65 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define size 100
int small(int arr[],int k,int n);
void selection(int arr[],int n);
int small(int arr[],int k,int n)
{
int pos=k,small=arr[k],i;
for(i=k+1;i<n;i++)
{
if(arr[i]<small)
{
small=arr[i];
pos=i;
}
}
return pos;
}
void selection(int arr[],int n)
{
int k,pos,temp;
for(k=0;k<n;k++)
{
pos=small(arr,k,n);
temp=arr[k];
arr[k]=arr[pos];
arr[pos]=temp;
}
}
int main()
{
int arr[size],num,i,n,found=0,beg,end,mid;
printf("enter the number of elements in an array:");
scanf("%d",&n);
printf("\n Enter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
selection(arr,n);
printf("\n the sorted array is: \n");
for(i=0;i<n;i++)
printf("%d\n",arr[i]);
printf("\n Enter the number to be searched:");
scanf("%d",&num);
beg =0,end = n-1;
while(beg<end)
{
mid=(beg+end)/2;
if(arr[mid] == num)
{
printf("\n %d is present at array at position %d",num,mid+1);
found==1;
break;
}
else if(arr[mid]>num)
end=num-1;
else
beg=num+1;
}
if(beg>end && found==0)
printf("\n %d does not exist in array",num);
return 0;
}