fork(4) download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <malloc.h>
  4.  
  5. void print(int *num, int n)
  6. {
  7. int i;
  8. for ( i = 0 ; i < n ; i++)
  9. printf("%d ", num[i]);
  10. printf("\n");
  11. }
  12.  
  13. int*permute(int*i,int h)
  14. {
  15. int temp = *i;
  16. *i = *(i+h);
  17. *(i+h) = temp;
  18. return i+1;
  19.  
  20. }
  21. void recursive_permute(int*i,int *j,int n)
  22. {
  23. if((j-i)==n-1) {print(i,n);return;};
  24.  
  25. int *tmparray=(int*)malloc(n*sizeof(int));
  26. memcpy(tmparray,i,n*sizeof(int));
  27. recursive_permute(tmparray,tmparray+(j-i+1),n);
  28.  
  29. for (int h=1;h<n-(j-i);h++) recursive_permute(tmparray,permute(tmparray+(j-i),h),n);
  30. }
  31.  
  32. int main()
  33. {
  34. int num[100];
  35. int *ptr;
  36. int temp;
  37. int i, n, j;
  38. printf("\nHow many number you want to enter: ");
  39. scanf("%d", &n);
  40. printf("\nEnter a list of numbers to see all combinations:\n");
  41. for (i = 0 ; i < n; i++)
  42. scanf("%d", &num[i]);
  43. printf("my recursive method ---------------------------\n");
  44. recursive_permute(num,num,n);
  45.  
  46. printf("your method -----------------------------------\n");
  47.  
  48. for (j = 1; j <= n; j++) {
  49. for (i = 0; i < n-1; i++) {
  50. temp = num[i];
  51. num[i] = num[i+1];
  52. num[i+1] = temp;
  53. print(num, n);
  54. }
  55. }
  56. return 0;
  57. }
Success #stdin #stdout 0s 2248KB
stdin
4 1 2 3 4
stdout
How many number you want to enter: 
Enter a list of numbers to see all combinations:
my recursive method ---------------------------
1 2 3 4 
1 2 4 3 
1 3 2 4 
1 3 4 2 
1 4 2 3 
1 4 3 2 
2 1 3 4 
2 1 4 3 
2 3 1 4 
2 3 4 1 
2 4 1 3 
2 4 3 1 
3 1 2 4 
3 1 4 2 
3 2 1 4 
3 2 4 1 
3 4 1 2 
3 4 2 1 
4 1 2 3 
4 1 3 2 
4 2 1 3 
4 2 3 1 
4 3 1 2 
4 3 2 1 
your method -----------------------------------
2 1 3 4 
2 3 1 4 
2 3 4 1 
3 2 4 1 
3 4 2 1 
3 4 1 2 
4 3 1 2 
4 1 3 2 
4 1 2 3 
1 4 2 3 
1 2 4 3 
1 2 3 4