-
Notifications
You must be signed in to change notification settings - Fork 2
/
Array_Binary_Search.c
74 lines (65 loc) · 1.52 KB
/
Array_Binary_Search.c
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
67
68
69
70
71
72
73
74
// author: jaydattpatel
#include <stdio.h>
#include<stdlib.h>
void sortarray(int arr[],int size)
{
int i = 0 ;
while(i<(size-1))
{
if(arr[i] > arr[i+1])
{
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
i = -1;
}
i++;
};
}
void getarrdata(int arr[],int size)
{
for(int i=0;i<size;i++)
do{
arr[i] = rand()%100;
}while(arr[i] == 0);
}
void display(int arr[],int size)
{
for(int i=0;i<size;i++)
printf("%d. %d\n",i,arr[i]);
}
int binarysearch(int arr[],int size,int search_data)
{
int low=0, high=size-1,mid;
int loop_count=0;
while(low<=high)
{
loop_count++;
mid = (high+low)/2;
if(arr[mid] == search_data)
{
printf("\nBinary Loop counts: %d\n",loop_count);
return (mid);
}
if(arr[mid] > search_data)
high = mid-1;
if(arr[mid] < search_data)
low = mid+1;
}
printf("\nLoop: %d\n",loop_count);
return (-1);
}
int main( )
{
int arr[10];
int data=0, loop_count, position;
int size = sizeof(arr)/sizeof(arr[0]);
getarrdata(arr,size);
sortarray(arr,size);
display(arr,size);
printf("Enter data to search position:");
scanf("%d",&data);
position = binarysearch(arr,size,data);
printf("Data %d is at position %d",data,position);
return 0;
}