冒泡排序输出未排序

时间:2017-04-22 03:31:19

标签: c++ sorting output bubble-sort

我的代码在放入int main()函数时有效但当我将它作为另一个函数(void bubbleSort)实现时,输出显示它就像没有完成排序一样。

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] <<' ';
}
}

我可能做错了什么?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您不能将完整数组作为参数传递给c ++函数,只能传递指向数组中第一个元素的指针。因此,您需要一些方法来告诉函数该数组的长度。将其作为另一个参数传递的一种方法(如下所示)。对其他/更好的方法进行了一些讨论和建议here

例如,如果您不小心将错误的length参数传递给这些函数,它们将开始对阵列所在的内存块之后存在的任何内存进行操作。

#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;
}