2014-04-05 4 views
1

배열을 정렬해야하는 작은 프로그램을 작성했습니다. 내가 그것을 실행할 때, 그것은 일을하지만 배열에 난수를 추가하는 것 같다. 또한 제목에 오류가 표시됩니다.런타임 검사 오류 # 02, 배열에 임의의 숫자가 추가되었습니다.

#include "stdafx.h" 
#include <iostream> 
#include <algorithm> 

void printArray(int nArray[], int nSize) { 
using namespace std; 
for (int jjj = 0; jjj <= nSize; jjj++) 
    cout << nArray[jjj] << " "; 
cout << endl; 
} 

void sortArray(int nArray[], int nSize, bool bPrint) { // bPrint is used to wether print after every step or not 

for (int nStartIndex = 0; nStartIndex < nSize; nStartIndex++) { // Durch jeden Teil des Arrays gehen 
    int nSmallestIndex = nStartIndex; // Den aktuellen Startindex als kleinsten nehmen 

    for (int nCurrentIndex = nStartIndex + 1; nCurrentIndex <= nSize; nCurrentIndex++) { 
     if (nArray[nCurrentIndex] < nArray[nSmallestIndex]) 
      nSmallestIndex = nCurrentIndex; 
    } 
    using namespace std; 

    swap(nArray[nStartIndex], nArray[nSmallestIndex]); 
    if (bPrint) { 
     cout << "Swapping " << nArray[nStartIndex] << " and " << nArray[nSmallestIndex] << endl; 
     printArray(nArray, nSize); 
    } 
    } 

} 

int main() { 
    const int nSize = 7; 
    int nArray[nSize] = { 3, 1, 5, 8, 2, 4, 6 }; 
    printArray(nArray, nSize); 
    sortArray(nArray, nSize, true); 
    std::cout << std::endl; 
    system("pause"); 
    return 0; 
} 
+0

std :: sort() 만 사용하면됩니다. –

+0

'nCurrentIndex <= nSize'가 올바르지 않습니다. –

답변

0

이 두 번 당신이 <= nSize을 가지고, 그것은 < nSize해야합니다. C++에서 배열의 크기가 N이면 유효한 인덱스는 0에서 N-1입니다.

0

for 루프 조건이 잘못되었습니다. <= nSize이 아닌 < nSize이어야합니다. 이것은 추가 무작위 요소가 인쇄되는 이유를 설명합니다.

for (int jjj = 0; jjj < nSize; jjj++) 
    cout << nArray[jjj] << " "; 
관련 문제