Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.77 KB | None | 0 0
  1. /**
  2.  * helpers.c
  3.  *
  4.  * Helper functions for Problem Set 3.
  5.  */
  6.  
  7. #include <cs50.h>
  8.  
  9. #include "helpers.h"
  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.     // TODO: implement a searching algorithm
  17.  
  18.     while(n > 0)
  19. {
  20.     int m;
  21.     int l;
  22.     int r;
  23.  
  24.     l = 0;
  25.     r = n - 1;
  26.     // find the  middle.
  27.     m = (l + r) / 2;
  28.  
  29.   //check if needle is found and exit .
  30.     if(values[m] == value)
  31.     {
  32.         return true;
  33.     }
  34.  
  35.   //check if present middle is greater than needle
  36.     else if(values[m] > value)
  37.     {
  38.         //move bound to right of middle
  39.         l = 0;
  40.         r = m - 1;
  41.      //find new middle
  42.         m = (l + r) / 2;
  43.     }
  44.  
  45.     //check if middle less than neddle
  46.     else if(values[m] < value)
  47.     {
  48.         //move bound to behind middle
  49.         l = m + 1;
  50.         r = n - 1;
  51.         m = (l + r) / 2;
  52.     }
  53. }
  54.  
  55.     // if needle is not found ,exit
  56.     return false;
  57. }
  58.  
  59. /**
  60.  * Sorts array of n values.
  61.  */
  62. void sort(int values[], int n)
  63. {
  64.     // TODO: implement a sorting algorithm
  65.  
  66.     //go through the array for 0 to the penultimate
  67.        for(int i = 0; i < n - 2;i++)
  68.      {
  69.          //make i your min
  70.          int min = i;
  71.          //go through again
  72.         for(int j = i ; j < n - 1;j++)
  73.     {
  74.         //now make j your min
  75.         j = i;
  76.  
  77.  
  78.         //check for smallest value
  79.         if(values[j] < values[min])
  80.         {
  81.  
  82.             // get that value for your min
  83.            min = j;
  84.         }
  85.     }
  86.  
  87.     // check if value is equall to i'th position
  88.     if(min != i)
  89.     {
  90.         //swap.
  91.          int temp = values[i];
  92.           values[i] = values[min];
  93.           values[min ]= temp;
  94.     }
  95.  
  96.  
  97.  
  98.  
  99. }
  100.  
  101.  
  102.     return;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement