Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * helpers.c
- *
- * Helper functions for Problem Set 3.
- */
- #include <cs50.h>
- #include "helpers.h"
- /**
- * Returns true if value is in array of n values, else false.
- */
- bool search(int value, int values[], int n)
- {
- //return false immediately if n is non-positive
- if(n <= 0)
- {
- return false;
- }
- //initialize variables needed for binary search
- int start = 0, end = n-1;
- //iterate till all of the 'hay' has been searched
- while(start <= end)
- {
- //return true if found
- if(values[((start + end)/2)] == value)
- {
- return true;
- }
- //split in half and manipulate counters
- else if(values[((start + end)/2)] > value)
- {
- end = (start + end)/2 - 1;
- }
- else
- {
- start = (start + end)/2 + 1;
- }
- }
- //return false if not found
- return false;
- }
- /**
- * Sorts array of n values.
- */
- void sort(int values[], int n)
- {
- int temp, small = values[0], k = 0;
- if(n == 1)
- {
- return;
- }
- for(int i = 0; i < n; i++)
- {
- for(int j = i; j < n; j++)
- {
- if(values[j] < small)
- {
- small = values[j];
- k = j;
- }
- temp = values[k];
- values[k] = values[i];
- values[i] = temp;
- }
- }
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement