-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.c
125 lines (113 loc) · 2.54 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/**
* helpers.c
*
* Computer Science 50
* Problem Set 3
*
* Helper functions for Problem Set 3.
*/
#include <cs50.h>
#include "helpers.h"
#include <stdio.h>
#include <math.h>
/**
* Returns true if value is in array of n values, else false.
* Does Linear Search
*
* Checked all green with check50:
* https://sandbox.cs50.net/checks/a814b06b7c644323b4540a91cc2cde4d
*/
bool searchLinear(int value, int values[], int n)
{
while (n > 0)
{
int mid = round(n/2);
if (values[mid] == value) return true;
else if (values[mid] > value)
{
for (int i = mid; i > 0; i--)
{
if (values[i] == value) return true;
}
}
else if (values[mid] < value)
{
for (int i = mid; i < n; i++)
{
if (values[i] == value) return true;
}
}
n--;
}
return false;
}
/*
* Returns true if value is in array of n values, else false.
* Does Binary Search
*
* Checked all green with check50:
* https://sandbox.cs50.net/checks/362b3a508b12429ab2bada945152a231
*/
bool search(int value, int values[], int n)
{
if (n <= 0)
{
return false;
}
do
{
if (values[(n/2)] == value)
{
return true;
}
else if (values[(n/2)] > value)
{
int stack[(n/2)];
for (int i = 0; i < n/2; i++)
{
stack[i] = values[i];
}
return search(value, stack, n/2);
}
else
{
int length = n - (n/2) - 1;
int stack[length];
for (int i = 0; i < length; i++)
{
stack[i] = values[(n/2)+1+i];
}
return search(value, stack, length);
}
}
while (n > 0);
return false;
}
/**
* Sorts array of n values using Selection Sort
*/
void sort(int values[], int n)
{
for (int i = 0; i < (n - 1); i++)
{
bool found = false;
int min = values[i];
int minPos = 0;
int temp = 0;
for (int j = i + 1; j < n; j++)
{
if (values[j] < min)
{
min = values[j];
minPos = j;
found = true;
}
}
if (found)
{
temp = values[i];
values[i] = values[minPos];
values[minPos] = temp;
}
}
}