2014-04-05 21 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,則有效索引爲0N-1

0

for-loop條件不正確 - 應爲< nSize而不是<= nSize。這解釋了爲什麼要打印一個附加的隨機元素。

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