Błąd segmentacji spowodowany rekurencją
Piszę program, który ma pobrać liczbę od 1-10 i wyświetlić wszystkie możliwe sposoby aranżacji liczb.
Wejście Ex: 3 wyjście:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Ilekroć wprowadzam 9 lub 10, program podaje błąd segmentacji i zrzuca rdzeń. Uważam, że problem polega na tym, że mój algorytm rekurencyjny jest nazywany zbyt wiele razy. Czy ktoś mógłby wskazać, w jaki sposób mogę ograniczyć liczbę koniecznych wywołań rekurencyjnych? Oto mój obecny kod:
void rearange(int numbers[11], int index, int num, int fact) {
int temp = numbers[index];
numbers[index] = numbers[index-1];
numbers[index-1] = temp;
int i;
for (i = 1; i <= num; ++i) // print the current sequence
{
printf("%d ", numbers[i]);
}
printf("\n");
fact--; // decrement how many sequences remain
index--; // decrement our index in the array
if (index == 1) // if we're at the beginning of the array
index = num; // reset index to end of the array
if (fact > 0) // If we have more sequences remaining
rearange(numbers, index, num, fact); // Do it all again! :D
}
int main() {
int num, i; // our number and a counter
printf("Enter a number less than 10: ");
scanf("%d", &num); // get the number from the user
int numbers[11]; // create an array of appropriate size
// fill array
for (i = 1; i <= num; i++) { // fill the array from 1 to num
numbers[i] = i;
}
int fact = 1; // calculate the factorial to determine
for (i = 1; i <= num; ++i) // how many possible sequences
{
fact = fact * i;
}
rearange(numbers, num, num, fact); // begin rearranging by recursion
return 0;
}