i have following code
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int a[] = {2, 1, 4, 3, 5, 6, 7, 9, 8, 10, 11};
int n = sizeof(a) / sizeof(int);
int k=0;
for (int i = 0; i < n; i++)
{
k = i + rand() % (n-1-i);
int s = a[i];
a[i] = a[k];
a[k] = s;
}
for (int i = 0; i < n; i++)
{
cout << a[i] << " " << endl;
}
return 0;
}
but it gives me runtime error,i know there is a lot of method in internet ,just i choose such simple for exam preparation in university,please help me what is wrong?
n = 11. When i = 10, that’s a k= i+rand() % 0;
Mod by zero is undefined and can operate a number of different ways. I’ve seen it equivalent to mod
infinity, so it would be returning k as i+rand() which would lead to your out-of-bounds error.