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"
- #include "stdio.h"
- /**
- * Returns true if value is in array of n values, else false.
- */
- bool search(int value, int values[], int n)
- {
- // declare search variables
- int start_point = 0; // start point on where to begin search
- int search_phase = 0; // whether we are starting a search or searching through the array now
- int current_search = 0; // the current search index we are on.
- int search_direction = 0; // the current direction we jump when searching the array. 0 = right. 1 = left
- // negative number passed through somehow - return false.
- if(n<0)
- {
- return false;
- }
- // get minimum point
- if(start_point==0)
- {
- start_point=n/2;
- }
- while(value<values[start_point] && start_point > 1)
- {
- start_point=start_point/2;
- }
- //Set up current point.
- if(search_phase==0)
- {
- if(value>values[start_point] || start_point <= 1)
- {
- if(current_search==0)
- {
- current_search=start_point;
- }
- }
- search_phase=1;
- }
- // set the direction on where to jump.
- // 0 = right, 1 = left.
- if(search_phase==1)
- {
- if(values[current_search] < value)
- {
- search_direction=0;
- }
- else
- {
- search_direction=1;
- }
- // scale the current search upward (right) as we haven't found
- // the needle yet.
- while(current_search<n && search_direction == 0)
- {
- if(values[current_search]!=value)
- {
- current_search++;
- }
- else
- {
- // We found the needle!
- return true;
- }
- }
- // scale the current search downward (left) as we haven't found
- // the needle yet.
- while(current_search>=0 && search_direction == 1)
- {
- if(values[current_search]!=value)
- {
- current_search--;
- }
- else
- {
- // We found the needle!
- return true;
- }
- }
- }
- // return false so we don't get in a forever loop.
- return false;
- }
- /**
- * Sorts array of n values.
- */
- void sort(int values[], int n)
- {
- // declare search position variables
- int position;
- int swap;
- // search and sort the array.
- for(int i = 0; i < (n - 2); i++)
- {
- for(int check = 0, look = 1; look < n; look++, check++)
- {
- position = check;
- if(values[position]>values[look])
- {
- position=look;
- }
- // swap the values around per selected position.
- if(position != check)
- {
- swap = values[check];
- values[check] = values[position];
- values[position] = swap;
- }
- }
- }
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement