Question

My problem is that I have two functions and one of the functions calls the other and because it does this several of times(rec), i want to save the value im getting in the second function (callled Mergesort in my case). I'm actually sorting a list using Merge Sort, but im interested in knowing the amount of inversions, so I want to return an int, but i dont see how I can store the value, so i can plus all the values together in the end to get the amount of inversions (yes i know there exists a O(n^2) algorithm to find this). I suppose most of u know the MergeSort algorithm so im not going to write it all up, but from the below code u might get an idea of what im looking for. if it doesnt help, then try to answer my question from what i explained above :)

public ArrayList MergeMerge(ArrayList A, int e, int a){
     s=...;
     MergeMerge(A,e,a);
     MergeMerge(A,e-1,a);
     MergeSort(A,e,r,s);

public ArrayList Mergesort (ArrayList A, int e, int a, int s) {
     ...
     int inversions=0;
     for (....)
         ....
         else {
            ...
            inversions=inversions+(s-i);
            }
Was it helpful?

Solution

You can use return values to keep track of this. Here's a generic example:

int myRecursiveMethod() {

    ...

    // Base case
    if (someCondition) { return 1; }

    // Otherwise
    return myRecursiveMethod() + myRecursiveMethod() + 1;
}


int totalCount = myRecursiveMethod();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top