# pset3: selection sort and binary search

I've been trying to implement those two function whole day and something seems to not be working because the printf function I wrote in find.c outputs 9,8,7,6,5,6,7,8,9 when I input the numbers from 9 to 1 as straws. I think the problem comes when value > m but I can't find a solution, so I'm hoping any of you guys gives me a tip.

The code with the two functions:

``````/**
* helpers.c
*
* Computer Science 50
* Problem Set 3
*
* 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)
{
int min = 0;
int max = n - 1;
// TODO: implement a searching algorithm
while(min <= max)
{
int midpoint = (min + max) / 2;
if (value == values[midpoint])
{
return true;
}
else if (value > values[midpoint])
{
min = midpoint + 1;
}
else if (value < values[midpoint])
{
max = midpoint - 1 ;
}
}
return false;
}

/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
// TODO: implement an O(n^2) sorting algorithm
for(int i = 0; i < n; i++)
{
int min = i;
for(int j = i + 1; j < n; j++)
{
if(values[j] < values[min])
{
min = j;
}
}
if(min != i)
{
values[min] = values[i];
}
}
}
``````
• By the way, the code goes through check50 without giving any errors. Aug 12, 2016 at 23:14

I figured it out. It seems like I didn't manage to swap `values[i]` and `values[min]` in selection sort the right way, so I did a bit of researching and saw that I need a third integer to do that. Here is the fixed code:

``````/**
* helpers.c
*
* Computer Science 50
* Problem Set 3
*
* 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)
{
int min = 0;
int max = n - 1;
// TODO: implement a searching algorithm
while(min <= max)
{
int midpoint = (min + max) / 2;
if (value == values[midpoint])
{
return true;
}
else if (value > values[midpoint])
{
min = midpoint + 1;
}
else if (value < values[midpoint])
{
max = midpoint - 1 ;
}
}
return false;
}

/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
// TODO: implement an O(n^2) sorting algorithm
for(int i = 0; i < n; i++)
{
int min = i;
for(int j = i + 1; j < n; j++)
{
if(values[j] < values[min])
{
min = j;
}
}
if(min != i)
{
int swap = values[min];
values[min] = values[i];
values[i] = swap;
}
}
}
``````