Reputation:
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?
Upvotes: 0
Views: 297
Reputation: 1551
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.
Upvotes: 0
Reputation: 308121
You might want to ask yourself what the result of %(n-1-i)
will be for all possible values of i
.
Upvotes: 1
Reputation: 62053
I think rand()%(n-1-i)
will give you a divide-by-zero for certain values if i
(like i == n-1).
Upvotes: 1