Shuffle an integer array
Write a function in c which shuffles the content of an integer array.
eg: Input array {11,22,33,44,55,66,77,88}
output array : {11,55,22,66,33,77,44,88}
please note first and last element should remain as it is.
eg: Input array {11,22,33,44,55,66,77,88}
output array : {11,55,22,66,33,77,44,88}
please note first and last element should remain as it is.
Since we need to shuffle elements between 0 and n-1(excluding them) we could do the following:
ReplyDelete1)Generate a random number bw (0,n-1).let it be x
Take the element arr[x] and swap it with arr[1]
2)Now generate a random number between (1,n-1)
take element arr[x] and swap it with arr[2]
....
Do this till we reach n-1th element.
@ankit correct,just for information we should use srand(time(NULL)) as seed value with rand function in c for generating random numbers..
ReplyDelete