Given an array, write a program to generate a random permutation of array elements.
Key point: from end to head
Read full article from Shuffle a given array | GeeksforGeeks
Key point: from end to head
To shuffle an array a of n elements (indices 0..n-1): for i from n - 1 downto 1 do j = random integer with 0 <= j <= i exchange a[j] and a[i]
void
randomize (
int
arr[],
int
n )
{
// Use a different seed value so that we don't get same
// result each time we run this program
srand
(
time
(NULL) );
// Start from the last element and swap one by one. We don't
// need to run for the first element that's why i > 0
for
(
int
i = n-1; i > 0; i--)
{
// Pick a random index from 0 to i
int
j =
rand
() % (i+1);
// Swap arr[i] with the element at random index
swap(&arr[i], &arr[j]);
}
}