C Program
#include<stdio.h> void shuffle(int *arr, int size){ int i, j, randomIndex, flag; int temp_arr[size], temp[size]; srand(time(0)); // random number generate i = 0; while(1){ randomIndex = rand() % size; if(i == 0) temp_arr[i++] = randomIndex; else{ flag = 0; for(j = 0; j <= i; j++){ if(temp_arr[j] == randomIndex){ flag = 1; break; } } if(flag == 0){ temp_arr[i++] = randomIndex; } } if(i == size) break; } for(i = 0; i < size; i++){ temp[i] = arr[temp_arr[i]]; } for(i = 0; i < size; i++){ arr[i] = temp[i]; } } int main(){ int i; int arr[] = {11, 33, 44, 22, 66, 55, 88, 77, 99}; printf("Shuffle"); for(i = 0; i < 9; i++) printf("%4d", arr[i]); shuffle(arr, 9); printf("\n"); for(i = 0; i < 9; i++) printf("%4d", arr[i]); return 0; }
C++ Program
#include<iostream> #include<time.h> using namespace std; void shuffle(int *arr, int size){ int i, j, randomIndex, flag; int temp_arr[size], temp[size]; srand(time(0)); // random number generate i = 0; while(1){ randomIndex = rand() % size; if(i == 0) temp_arr[i++] = randomIndex; else{ flag = 0; for(j = 0; j <= i; j++){ if(temp_arr[j] == randomIndex){ flag = 1; break; } } if(flag == 0){ temp_arr[i++] = randomIndex; } } if(i == size) break; } for(i = 0; i < size; i++){ temp[i] = arr[temp_arr[i]]; } for(i = 0; i < size; i++){ arr[i] = temp[i]; } } int main(){ int i; int arr[] = {11, 33, 44, 22, 66, 55, 88, 77, 99}; cout<<endl<<"Shuffle "; for(i = 0; i < 9; i++) cout<<arr[i]<<" "; shuffle(arr, 9); cout<<endl; for(i = 0; i < 9; i++) cout<<arr[i]<<" "; return 0; }
Output :-
0 Comments