Skip to content

Instantly share code, notes, and snippets.

@MohamedTaha98
Created June 10, 2017 14:27
Show Gist options
  • Save MohamedTaha98/1aa2ce78aaaf4a734aa80f3a12e0f1e8 to your computer and use it in GitHub Desktop.
Save MohamedTaha98/1aa2ce78aaaf4a734aa80f3a12e0f1e8 to your computer and use it in GitHub Desktop.
CS50
/**
* helpers.c
*
* Computer Science 50
* Problem Set 3
*
* 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)
{
int midpoint, min = 0, max = n;
midpoint = (min + max) / 2;
if (value == values[midpoint])
return true;
while (value != values[midpoint])
{
if (max < min)
return false;
else
{
if (value > values[midpoint])
{
min = midpoint + 1;
midpoint = (min + max) / 2;
}
else if (value < values[midpoint])
{
max = midpoint - 1;
midpoint = (min + max) / 2;
}
if (value == values[midpoint])
return true;
}
}
return false;
}
/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
int min;
for (int i = 0; i < n; i++)
{
min = i;
for (int j = i; j < n; j++)
{
if (values[j] < values[min])
min = j;
}
if (min != i)
{
int sw = values[min];
values[min] = values[i];
values[i] = sw;
}
}
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment