-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.c
65 lines (61 loc) · 1.24 KB
/
helpers.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
/**
* helpers.c
*
* Computer Science 50
* Problem Set 3
*
* Helper functions for Problem Set 3.
*/
#include <cs50.h>
#include "helpers.h"
/**
* Returns true if value is in array of n values, else false.
*/
int binarySearch(int value,int values[],int min,int max);
bool search(int value, int values[], int n)
{
int min = values[0];
int max = values[n - 1];
binarySearch(value, values[], min, max);
return 0;
}
int binarySearch(int value,int values[],int min,int max) {
int midpoint;
if(max < min){
return -1;
}
else
{
midpoint = (min + max)/2;
if(values[midpoint] < value)
{
binarySearch(value, values[], midpoint + 1, max);
}
else if(values[midpoint] > value){
binarySearch(value, values[], min, midpoint - 1);
}
else
{
return 1;
}
}
}
/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
int element;
for(int i = 0; i < n; i++)
{
element = values[i];
int j = i;
while((j > 0) && (values[j - 1] > element))
{
values[j] = values[j - 1];
j = j - 1;
}
values[j] = element;
}
return;
}