#include <stdio.h>
// Function to swap elements
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to find the possible permutations.
// Initial value of idx is 0.
void permutations(int res[][100], int* arr, int idx, int size, int* resSize) {
// Base case: if idx reaches the size of the array,
// add the permutation to the result
if (idx == size) {
for (int i = 0; i < size; i++) {
res[*resSize][i] = arr[i];
}
(*resSize)++;
return;
}
// Permutations made by swapping each element
// starting from index `idx`
for (int i = idx; i < size; i++) {
// Swapping
swap(&arr[idx], &arr[i]);
// Recursive call to create permutations
permutations(res, arr, idx + 1, size, resSize);
// Backtracking
swap(&arr[idx], &arr[i]);
}
}
// Function to get the permutations
void permute(int* arr, int size, int res[][100], int* resSize) {
permutations(res, arr, 0, size, resSize);
}
// Driver code
int main() {
int arr[] = { 1, 2, 3 };
int res[100][100]; // 2D array to store permutations
int resSize = 0;
permute(arr, 3, res, &resSize);
// Printing result
for (int i = 0; i < resSize; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", res[i][j]);
}
printf("\n");
}
return 0;
}