Advertisement
Guest User

Untitled

a guest
Feb 1st, 2017
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.80 KB | None | 0 0
  1. /**
  2.  * helpers.c
  3.  *
  4.  * Helper functions for Problem Set 3.
  5.  */
  6.  
  7. #include <cs50.h>
  8. #include "helpers.h"
  9.  
  10.  
  11. /**
  12.  * Returns true if value is in array of n values, else false.
  13.  */
  14. bool search(int value, int values[], int n)
  15. {
  16.     int min = 0;
  17.     int max = n-1;
  18.     if(binary(value,values,min,max) == true)
  19.     {
  20.         return true;
  21.     }
  22.     else
  23.     {
  24.     return false;
  25.     }
  26. }
  27.  
  28. bool binary(int value, int values[], int min, int max)
  29. {
  30.     int current_index = ((min+max)/2);
  31.     if(min > max)
  32.     {
  33.         return false;
  34.     }
  35.     else if(values[current_index] == value)
  36.     {
  37.         return true;
  38.     }
  39.     else if(values[current_index] < value)
  40.     {
  41.         min = current_index + 1;
  42.         return binary(value,values,min,max);
  43.     }
  44.     else if(values[current_index] > value)
  45.     {
  46.         max = current_index - 1;
  47.         return binary(value,values,min,max);
  48.     }
  49.     else
  50.     {
  51.         return false;
  52.     }
  53.    
  54. }
  55.  
  56. /**
  57.  * Sorts array of n values.
  58.  */
  59. void sort(int values[], int n)
  60. {
  61.     int temp;
  62.     int max_value = 0;
  63.     int s = 0;
  64.     //Find Max Value
  65.     for(int j = 0;j < n;j++)
  66.     {  
  67.         if(values[j] > max_value){
  68.             max_value = values[j];
  69.         }
  70.     }
  71.     //Fill Arrays with proper counts
  72.     int array_holder[max_value];
  73.     for(int c = 0;c < max_value;c++)
  74.     {
  75.         array_holder[c]=0;
  76.     }
  77.     for(int i = 0;i < n;i++)
  78.     {  
  79.         temp = values[i];
  80.         array_holder[temp] = array_holder[temp]+1;
  81.     }
  82.     for(int k = 0; k <= max_value; k++)
  83.     {
  84.         if(array_holder[k] == 0)
  85.         {
  86.             k++;
  87.         }
  88.         while(array_holder[k] > 0)
  89.         {
  90.             values[s] = k;
  91.             array_holder[k] = array_holder[k] - 1;
  92.             s++;
  93.         }
  94.     }
  95.    
  96.     return;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement