#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?
n * n
times. also, I'm not sure why you're wrappingprintf("\n")
in afor
loop that iterates once, why you're resettingi
to 0 when it's > 5. did you see the pseudocode of bubble sort here?