I am writing a sort function to implement a bubble sort in C but it is not sorting the given array. Here is the following code. I am using a void function so I cannot return the array and have to make changes in the existing array. The code compiles well and runs but it does not sort the array.
void sort(int values[], int n)
{
// TODO: implement an O(n^2) sorting algorithm
for(int i = 0; i < n; i++)
{
int sp = 0;
for(int j = 0; j < n; j++)
{
if (values[i] > values[i + 1])
{
int first_val = values[i];
int second_val = values[i + 1];
values[i] = second_val;
values[i + 1] = first_val;
sp = 1;
}
}
if (sp == 0)
{
break;
}
}
}
In Bubble Sort, n-1 comparisons will be done in 1st pass, n-2 in 2nd pass, n-3 in 3rd pass and so on. So the total number of comparisons will be
(n-1)+(n-2)+(n-3)+.....+3+2+1
Sum = n(n-1)/2
i.e O(n2)
So two things you need to change in your code :-