# Pset3 - Problem with Bubble Sort

I've tried to write an implementation of bubble sort.

I deliberately created it in a separate file outside of helpers.c, just to make sure it works, before incorporating into helpers.c

It doesn't work! I don't understand why not. I've worked through what I think should be happening with a pen and paper. So, I'm stuck.

My code is below. I've left in my commentary, so you can understand my logic a bit. Also, please forgive me if I haven't managed to input the code properly - I'm assuming I can just copy and paste from the ide.

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

void sort(int values[], int n)
{
for(int i = 0; i < n-1; i++) // Note: "i < n-1" because we are checking pair-wise; therefore only need to get to penultimate place in array
{
bool noswap = 0; // Introducing variable that tests whether we swapped any pairs of numbers on any run-through the "inner" loop
for(int j = 0; j < (n - 1 - i); j++)
{
if(values[j] > values[(j+1)])
{
int temp  = values[j];
values[j] = values[(j+1)];
values[j] = temp;
noswap = 1;
}
}
if (noswap == 0) // If no pairs of numbers were swapped, we can break, without having to back through the outer loop again - improving efficiency
{
break;
}
}
return;
}

// This is a short programme that uses the "sort" function written above, to test whether it works

int main()
{
int arr[] = {9, 4, 2, 3, 1};
sort(arr, 5);
for(int i = 0; i < 5; i++)
{
printf("arr position %d = %d\n", i, arr[i]);
}
}
``````

And here is the output: In your swap part, you assign to `values[j]` twice, second should be `values[j+1]`