0

I've been working on implementing a recursive version of heap's algorithm. Here is the link to the pseudocode: http://en.wikipedia.org/wiki/Heap%27s_algorithm

Everything has been going fine until I get to the recursive part. I know I haven't put in swapping elements yet but I haven't gotten that far. The run fails without showing an error until I use the gcc debugger which tells me that there has been a segmentation fault. Here is my code:

#include <string>
#include <iostream>
using namespace std;

string* permute(int n, string array[2]){
    if (n==1){
        return array;
    }
    else{
        for(int c=1; c<=n;c++){
            permute(n--,array);
        }
    }
}

int main() {
    string array[2]={"a","b"};
    permute(2,array);
    return 0;
}
1
  • 1
    How is the return statement in the else part of function permute? And why are you decrementing n inside the loop which runs from 1 to n? Commented Jul 7, 2014 at 14:35

4 Answers 4

5

Let aside the fact that the entire implementation seems wrong, the direct reason for the runtime exception that you're experiencing is your recursive call to permute(2,array), which eventually leads to a stack overflow. This happens because you are calling it with n-- instead of --n (or more precisely, n-1).

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, I'm a beginner so help is always appreciated!
@user2514631: You're welcome :) There's a lot more work to be done up there.
2

try permute( --n, array ) you are passing a copy of 2 not the decrement

Comments

1

You have to use prefix subtraction:

change:

 permute(n--,array);

to:

 permute(--n,array);

In this way, you first decrement 'n' and then call permute.

In first case you never subtract and you have an infinite recursion.

Comments

0

You shouldn't be post-decrementing n in your recursive call, pre-decrement instead:

permute(--n,array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.