Created
August 30, 2014 12:56
-
-
Save robsbots/68ab63f3347240e5959d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** * helpers.c * * Computer Science 50 * Problem Set 3 * * Helper functions for Problem Set 3. */ | |
#include <cs50.h> | |
#include <math.h> | |
#include "helpers.h" | |
/** * Returns true if value is in array of n values, else false. */ | |
bool search(int value, int array[], int n) { | |
// TODO: implement a searching algorithm | |
int high, low, i; | |
high = n; | |
low = 0; | |
sort(array, n); | |
i = (high + low)/2; | |
if (value < array[0] || value > array[n - 1]) | |
return false; | |
else | |
while(array[i]) { | |
if(array[i] == value) | |
return true; | |
else | |
if(value > array[i]) | |
low = i; | |
else | |
high = i; | |
i = (high + low)/2; | |
} | |
return 0; | |
} | |
/** | |
* Sorts array of n values. | |
*/ | |
void sort(int values[], int n) | |
{ | |
// TODO: implement an O(n^2) sorting algorithm | |
for (int i = 0;i < n;i++) | |
{ | |
while (values[i] > values[i + 1] && (i + 1) < n) | |
{ | |
int temp = values[i]; | |
values[i] = values[i + 1]; | |
values[i + 1] = temp; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment