-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.c
More file actions
99 lines (85 loc) · 1.36 KB
/
binarysearch.c
File metadata and controls
99 lines (85 loc) · 1.36 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ARR_SIZE 10
int swap(int *a, int *b)
{
int temp;
int swapped = 0;
if(*a > *b)
{
temp = *a;
*a = *b;
*b = temp;
swapped = 1;
}
return swapped;
}
int main(void)
{
srand(time(NULL));
int key = 5;
int min, max, match;
int arr[ARR_SIZE];
int *a_ptr;
int key_index = -1;
a_ptr = arr;
printf("BUBBLESORT\n");
for(int i = 0; i < ARR_SIZE; i++)
{
*a_ptr = rand()%10;
a_ptr++;
}
a_ptr = arr;
printf("BEFORE SORT: [ ");
for(int i = 0; i < ARR_SIZE; i++)
{
printf("%d, ", *a_ptr);
a_ptr++;
}
printf(" ]\n");
for(int i = 0; i < ARR_SIZE; i++)
{
a_ptr = arr;
for(int j = 0; j < (ARR_SIZE - 1) - i; j++)
{
swap(a_ptr, a_ptr+1);
a_ptr++;
}
}
a_ptr = arr;
printf("AFTER SORT: [ ");
for(int i = 0; i < ARR_SIZE; i++)
{
printf("%d, ", arr[i]);
}
printf(" ]\n");
min = 0;
max = ARR_SIZE-1;
match = (ARR_SIZE-1)/2;
printf ("MIN: %d\nMID: %d\nMAX: %d\n", arr[min], arr[match], arr[max]);
while(min < max && key_index == -1)
{
if(arr[match] == key)
{
key_index = match;
}
else if(arr[match] > key)
{
max = match - 1;
}
else if(arr[match] < key)
{
min = match + 1;
}
match = (min + max)/2;
}
if(key_index >= 0){
printf("Key is at index %d.\n", key_index);
}
else
{
printf("Key is not present in this data set.\n");
}
return 0;
}