Reputation: 452
My code works when put in the int main() function but when I implement it as another function (void bubbleSort) the output displays it as if there was no sorting done.
void bubbleSort(int numeros[])
{
int store = 0;
int length = ARRAY_SIZE(numeros);
for(int i=0; i<(length-1); i++)
{
for(int j=0; j<(length-i-1); j++)
{
if(numeros[j] < numeros[j+1])
{
store = numeros[j];
numeros[j] = numeros[j+1];
numeros[j+1] = store;
}
}
}
for(int m=0; m<1000; m++)
{
cout << numeros[m] <<' ';
}
}
What could I have possibly done wrong? Any help would be greatly appreciated.
Upvotes: 0
Views: 173
Reputation: 5419
You can't pass a full array as an argument to a c++ function, only a pointer to the first element in the array. As a result you need some way to tell the function how long the array is. One way it to pass that in as another argument (as shown below). There is some discussion and suggestions of other/better ways to do it here.
For example if you accidentally pass in the wrong length
argument to these functions they will start operating on whatever memory exists after the block of memory where your array is.
#include <iostream>
using namespace std;
void printArray(int array[], int length) {
for(int i=0; i<length; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void bubbleSort(int numeros[], int length) {
int store = 0;
for(int i=0; i<(length-1); i++) {
for(int j=0; j<(length-i-1); j++) {
if(numeros[j] < numeros[j+1]) {
store = numeros[j];
numeros[j] = numeros[j+1];
numeros[j+1] = store;
}
}
}
cout << "array at end of bubble sort: ";
printArray(numeros, length);
}
int main() {
int anArray[] = {1, 3, 2, 4, 6, 5, 10, 9, 7, 8};
int arraySize = sizeof(anArray)/sizeof(anArray[0]);
cout << "arraySize: " << arraySize << endl;
cout << "array before sort: ";
printArray(anArray, arraySize);
bubbleSort(anArray, arraySize);
cout << "array after sort: ";
printArray(anArray, arraySize);
return 0;
}
Upvotes: 1