2017-04-22 158 views
0

我的代码在放入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] <<' '; 
} 
} 

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

+3

'int length = ARRAY_SIZE(numeros);' - 把'std :: cout << length << std :: endl;'放在它后面。这可能会告诉你问题 –

回答

2

无法将完整数组作为参数传递给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; 
} 
+0

谁感谢这肯定会帮助 –

+0

@LeeMin不用担心。如果它回答您的问题,请考虑将其标记为已接受/正在提交。 – kabdulla