I am trying to write my own bubble sort algorithm as an exercise. I do not understand the two error messages. Can anyone point out the problem with my code?
// Bubble sort algorithm
#include <iostream>
#include <iomanip>
using namespace std;
void bubbleSort(int array[], int arraySize); // bubbleSort prototype
int main(void)
{
const int arraySize = 10;
int array[arraySize] = {2,3,6,5,7,8,9,3,7,4};
cout << "Unsorted: ";
for(int i = 0; i < arraySize; ++i)
cout << setw(5) << array[i];
cout << "Sorted: " << bubbleSort(array, arraySize);
}
void bubbleSort(int array[], int arraySize)
{
const int max = arraySize;
int swap = 0;
for(int i = 0; i < max; ++i)
{
if(array[i] > array[i + 1])
{
swap = array[i + 1];
array[i + 1] = array[i];
array[i] = swap;
}
else
break;
}
}
I see that you are using
So when you type
The compiler cannot disambiguate whether you are referring to the
std::swap
function or yourint swap
variable. In fact it looks like it assumed you were referring to the function and tried to somehow convert it to typeint
. Try renaming your variable to something else.In general, try to stay away from
using
directives, to avoid name collisions like this.This line is causing problem. It is better to change the name of
swap
local variable, as there exists already a function with same name, instd
namespace which is brought into scope by the lineusing namespace std;
which is to be avoided, anyway.I would also suggest you to declare the variable, inside the if-block where it is actually used:
Best practice: reduce the scope local variables by delaying their declarations, which means declare them where they are actually used. Do not declare them in the beginning of the function.
Another way to fix the problem in your code is to give the compiler a context which you can by doing this (though I wouldn't suggest this solution; it is just for you to know):
When you cast
swap
toint
, the compiler can know thatswap
refers to the local variable, not the function which is defined instd
namespace.The return type of the function is
void
. There is nothing to print for. If you need to print the sorted array, you need to iterate over the array elements after the function call.