我寫了一個用於marge排序數組的小算法。但我有問題。如何得到正確的答案合併2個排序的數組? C++
#include <iostream>
using namespace std;
int main() {
// main function started form here:
int firstArray[10] = {1,3,5,7,9,11,13,15,17,19};
int secondtArray[10] = {2,4,6,8,10,12,14,16,18,20};
int mergedArray[20];
int firstCounter=0 , secondtCounter=0 , mergedCounter=0;
while(firstCounter < 10 && secondtCounter < 10){
if(firstArray[firstCounter] < secondtArray[secondtCounter]){
mergedArray[mergedCounter] = firstArray[firstCounter];
firstCounter++;
} else {
mergedArray[mergedCounter] = secondtArray[secondtCounter];
secondtCounter++;
}
mergedCounter++;
}
while(firstCounter < 10) {
mergedArray[mergedCounter] = firstArray[firstCounter];
firstCounter++;
mergedCounter++;
}
while(secondtCounter < 10) {
mergedArray[mergedCounter];
secondtCounter++;
mergedCounter++;
}
for(int j=0; j<20; j++){
//cout << mergedArray[j] << endl;
}
cout << mergedArray[19];
return 0;
}
在outpout
數組mergedArray[19]
我得到這樣的:2686916
!
我不知道爲什麼我得到這個值。我該如何解決這個問題。爲什麼我得到這個價值。
這個:'mergedArray [mergedCounter];'作爲最後一個合併循環中的單個語句不會做太多工作。你忘了賦值部分。並注意你的編譯器警告說「代碼無效」會告訴你這一點。編譯時使用高警告級別,不要在彈出時忽略它們。 – WhozCraig
你編譯器可能發出警告:語句沒有效果[-Wunused-value] –