assuming there are no repeats: just change each element with all possible following elements, and recursively invoke the function.
void permute(int *array,int i,int length) {
if (length == i){
printArray(array,length);
return;
}
int j = i;
for (j = i; j < length; j++) {
swap(array+i,array+j);
permute(array,i+1,length);
swap(array+i,array+j);
}
return;
}
You can see the code with auxilary functions swap()
and printArray()
performing with a basic test case at ideone
Bonus: This is similar to the idea of fisher-yates shuffle, but in here – intead to swapping the element at i
with randomly chosen following element – you swap it with all of them – each at a time.