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)
- {
- // TODO: implement a searching algorithm
- while(n > 0)
- {
- int m;
- int l;
- int r;
- l = 0;
- r = n - 1;
- // find the middle.
- m = (l + r) / 2;
- //check if needle is found and exit .
- if(values[m] == value)
- {
- return true;
- }
- //check if present middle is greater than needle
- else if(values[m] > value)
- {
- //move bound to right of middle
- l = 0;
- r = m - 1;
- //find new middle
- m = (l + r) / 2;
- }
- //check if middle less than neddle
- else if(values[m] < value)
- {
- //move bound to behind middle
- l = m + 1;
- r = n - 1;
- m = (l + r) / 2;
- }
- }
- // if needle is not found ,exit
- return false;
- }
- /**
- * Sorts array of n values.
- */
- void sort(int values[], int n)
- {
- // TODO: implement a sorting algorithm
- //go through the array for 0 to the penultimate
- for(int i = 0; i < n - 2;i++)
- {
- //make i your min
- int min = i;
- //go through again
- for(int j = i ; j < n - 1;j++)
- {
- //now make j your min
- j = i;
- //check for smallest value
- if(values[j] < values[min])
- {
- // get that value for your min
- min = j;
- }
- }
- // check if value is equall to i'th position
- if(min != i)
- {
- //swap.
- int temp = values[i];
- values[i] = values[min];
- values[min ]= temp;
- }
- }
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement