# sort algorithm is working, but i finding it hard to implement in helpers.c

``````#include <stdio.h>
#include <cs50.h>

int main(void)
{
int values[12] = {10,2,14,5,7,4,3,13,15,22,8,24};
int i = 0;
int n = 12;
for(int x = 0; x < n*n; x++)
{
while(i<n-1)
{

if(values[i]>values[i+1])
{
int temp = values[i+1];
values[i+1] = values[i];
values[i] = temp;
i++;
for(int c = 0; c < n; c++)
{
printf("%i ",values[c]);
}
for(int a = 0; a < 1; a++)
{
printf("\n");
}

}

else
{
i++;
}

}
while(i >= 5)
{
i=0;
}
}
}
``````

So this is basically my bubble sort algorithm. And as it seems it works fine. While implementing it in helpers.c. i use n as a number of how long is array values, and values as an array.

This is how it looks:

``````/**
* 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)
{
// TODO: implement a searching algorithm
if(n < 0)
{
return false;
}
else
{
for(int i = 0; i < n; i++)
{
if(values[i]==value)
{
return true;
}
}
}
return false;
}

/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
int i = 0;
// TODO: implement an O(n^2) sorting algorithm
for(int x = 0; x < n*n; x++)
{
while(i<n-1)
{

if(values[i]>values[i+1])
{
int temp = values[i+1];
values[i+1] = values[i];
values[i] = temp;
i++;
for(int c = 0; c < n; c++)
{
printf("%i ",values[c]);
}
for(int a = 0; a < 1; a++)
{
printf("\n");
}

}

else
{
i++;
}

}
while(i >= 5)
{
i=0;
}
}

}
``````

And then i run ./generate 1000 50 | ./find 127 haystack[996] = haystack[997] = haystack[998] = haystack[999] = haystack[1000] =

Found needle in haystack!

I get his... Haystacks are empty, and sort seems is not executed... How i need to run it or change it for it to work?

• hi, @Vienas Du! you probably need to work more on the style of your code. see manual.cs50.net/style for tips! I don't see why you're iterating `n * n` times. also, I'm not sure why you're wrapping `printf("\n")` in a `for` loop that iterates once, why you're resetting `i` to 0 when it's > 5. did you see the pseudocode of bubble sort here?
– kzidane
Mar 18 '16 at 22:07
• n * n is done because maximum times it can go around is O(n2), so if array is 8 long, maximum times it could be going is 8*8. for loop iterates every time while loop is run, so it basically prints all array in the new line every time it is printed. 5 it just random number because it basically its only called then first while is false, it could be any number. Even if my algorithm is wrong i need help to how to implement it. I will modify it later, but i just cant get it working in helpers.c Mar 19 '16 at 0:13
• I mean then i try to get make find i get this error: helpers.c:57:12: error: implicitly declaring library function 'printf' with type 'int (const char *, ...)' [-Werror] printf("%c ",values[c]); Mar 19 '16 at 0:20