2017-04-22 127 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