0

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.

1
  • 1
    Check the indexing in your first loop again. Commented May 18, 2021 at 13:44

1 Answer 1

1

You are reading elements only from a[1], but your sorting begins from a[0].

Change

for (int i = 1; i < n; ++i)
{
    cin >> a[i];
}

to

for (int i = 0; i < n; ++i)
{
    cin >> a[i];
}

to read data also to a[0].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.