I was writing sorting algorithm when I encountered the following error.
Code:
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
int a[100];
cin >> n;
for (int i = 1; i < n; ++i) {
cin >> a[i];
}
//or use getlinee as getline (cin, fullName);
int swap_count = 0;
for (int i = 0; i < n - 1; ++i) {
if (a[i] > a[i + 1]) {
swap_count = swap_count + 1;
}
}
if (swap_count != 0) {
for (int p = n; p > 1; --p) {
for (int q = 0; q < p - 1; ++q) {
if (a[q] > a[q + 1]) {
int temp_var = a[q];
a[q] = a[q + 1];
a[q + 1] = temp_var;
}
}
}
}
for (int i = 0; i < n; ++i) {
cout << a[i] << " ";
}
return 0;
}
Input:
3
1 5 2
Output:
1 5 1878000832
On repeating with multiple values I found the last value of the series is being read wrong.
What is the reason for this problem and how do I resolve it?
Note: I know there are many alternative ways to input but I wanted to know why this one isn't working.