הנה משהו שעובד ב-C
זה הדבר הכי פשוט שהצלחתי להנדס, אחרי איסוף שברים בגוגל...
#include <stdio.h> #include <string.h> void swap(int* a,int* b) { char temp=*a; *a=*b; *b=temp; } int permute(int arr[], int len) { int key=len-1; int newkey=len-1; /*The key value is the first value from the end which is smaller than the value to its immediate right*/ while( (key>0)&&(arr[key] <= arr[key-1])) {key--;} key--; /*If key<0 the data is in reverse sorted order, which is the last permutation. */ if(key <0) return 0; /*arr[key+1] is greater than arr[key] because of how key was found. If no other is greater, arr[key+1] is used*/ newkey=len-1; while((newkey > key) && (arr[newkey] <= arr[key])) { newkey--; } swap(&arr[key],&arr[newkey]); /*variables len and key are used to walk through the tail, exchanging pairs from both ends of the tail. len and key are reused to save memory*/ len--; key++; /*The tail must end in sorted order to produce the next permutation.*/ while(len>key) { swap(&arr[len],&arr[key]); key++; len--; } return 1; } void main() { int test_array[]={1,2,3,4,5}; int size = sizeof(test_array)/sizeof(test_array[0]); int i; do { for (i = 0; i < size; ++i) printf("%u ", test_array); printf("\n"); } while(permute(test_array,size)); }