Jayasimha Reddy
Jayasimha Reddy

Reputation: 1

why the swap part is executing again after the function hit return statement

the code is working fine till end and i am getting a sorted array, but after sorting it is again executing swap part code , but the issue is getting solved by adding else to the swap method.

    if(i==0){
        return;
    }
    if(j<=i){
        if(arr[j]>arr[max]){
            max=j;             //finding the max element in array
        }
        SS(arr,i,j+1,max);
    }
    int temp = arr[i];
    arr[i] = arr[max];       //swapping the max element.
    arr[max] = temp;
    SS(arr, i - 1, 0, 0);
}

}

This is working:

    if(i==0){
        return;
    }
    if(j<=i){
        if(arr[j]>arr[max]){
            max=j;
        }
        SS(arr,i,j+1,max);
    }
    else{
    int temp = arr[i];
    arr[i] = arr[max];
    arr[max] = temp;
    SS(arr, i - 1, 0, 0);
    }
}

}

what are the differences ?

Upvotes: -1

Views: 33

Answers (1)

m.antkowicz
m.antkowicz

Reputation: 13581

Well, without going deep into the algorithm, you have additional i++; in the second if branch in the second example.

Moreover in the first example the swap will happen even if the j<=i condition is met because you did not add return - it will not happen in the second example.

Upvotes: 0

Related Questions