A function to generate a random permutation of arr[]
| 275 | |
| 276 | // A function to generate a random permutation of arr[] |
| 277 | static void randomize ( int arr[], int n ) |
| 278 | { |
| 279 | // Use a different seed value so that we don't get same |
| 280 | // result each time we run this program |
| 281 | srand ( time(NULL) ); |
| 282 | |
| 283 | // Start from the last element and swap one by one. We don't |
| 284 | // need to run for the first element that's why i > 0 |
| 285 | for (int i = n-1; i > 0; i--) |
| 286 | { |
| 287 | // Pick a random index from 0 to i |
| 288 | int j = rand() % (i+1); |
| 289 | |
| 290 | // Swap arr[i] with the element at random index |
| 291 | swap(&arr[i], &arr[j]); |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | /* time */ |
| 296 | #include <time.h> |