Pset3 Find, I am so confused and need some direction please

I am going round and round in circles with this pset, please can someone give me some direction, below is a copy of my code:

``````/**
* helpers.c
*
* Helper functions for Problem Set 3.
*/

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "helpers.h"

/**
* Returns true if value is in array of n values, else false.
*/
bool search(int value, int values[], int n)

// TODO: implement a searching algorithm
{
int low = 0;
int high = n-1;
int mid = low + ((high - low) / 2);

// while length of list is greater than two
while (n > 2)
{
// if middle of values is equal to value, return true
if (mid == value)
return true;

// else if middle of values is greater than value, look to the left
if (mid > value)
mid = low + ((mid-1 - low) / 2);

//else if middle of values is less than value, look to the right
if (mid < value)
mid = low + ((high - mid+1) / 2);
}

//else return false
return false;

// Swap function
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

/**
* Sorts array of n values.
*/
void sort(int values[], int n);

// TODO: implement an O(n^2) sorting algorithm

int current;
int swapd = n-1;

for(int i = 0; i < n-1; i++)
{
current = values[i];

if (current > i+1)
swap (current, i);

else //(swapd == 0);
return false;
}

}

return;
``````

In search, while loop should not be `(n>2)` (you don't change `n`), but something like `(low<=high)`, meaning "as long as search interval has elements".

`low + ((high - low) / 2)` could be just `(high + low) / 2`, and calculate that within the loop, just after the `while`.

You compare index `mid` to value `value`, but should compare `values[mid]` to `value`.

In the two comparison paths, do not assign to `mid`, but change `high` or `low` to `mid-1` or `mid+1`, respecively. As you recalculate `mid` at the beginning of the next loop iteration (two points above), it will be adjusted accordingly.

In sort, again you compare a value `values[i]` to an index `i+1`. Compare only values. swap function should receive pointers, like `swap(&values[i],&values[i+1])`

A O(n²) algorithm probably needs two nested loops.

Do not return in the loop, unless you are finished with sorting. return leaves the function.

• Thank you for this, have made changes but coming up with two errors now, but will post separate question as will need to show code again – Sofia Jan 25 '17 at 18:04