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

whoa 고마워하는 사람은 분명히 도와 줄 것이다 –

+0

@LeeMin 걱정하지 마라. 귀하의 질문에 대답을하면 그것을 승인/upvoting로 표시 고려하십시오. – kabdulla