A
A
Alexey Yakovlev2021-10-26 20:48:36
C++ / C#
Alexey Yakovlev, 2021-10-26 20:48:36

Some numbers and an error are displayed, what's wrong?

I wanted to implement the bubble sort algorithm like this:

#include <iostream>
using namespace std;

int main()
{
    short arr[8] = {2,3,1,5,8,4,7,6};

    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 8; j++)
        {
            if (arr[j + 1] < arr[j])
            {
                short tmp = arr[j + 1];
                arr[j + 1] = arr[j];
                arr[j] = tmp;
            }
        }
    }

    for (int i = 0; i < 8; i++)
    {
        cout << arr[i] << " ";
    }
}


An error is displayed Stack around the variable "arr" was corrupted, and in the console it is -13108 1 2 3 4 5 6 7

What did I do wrong, how to get rid of these numbers and what do they mean?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2021-10-26
@aleshaykovlev

The error, if translated, means: you have out of bounds of the array arr.
Watch carefully where you refer to it. Especially on arr[j + 1]. What values ​​can it take j? What is the size of the array and, accordingly, what indexes can be accessed?

R
Rsa97, 2021-10-26
@Rsa97

When j == 7, where does arr[j + 1] go?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question