jeudi 3 décembre 2015

multiple if without else not equivalent to if else? c++

Trying to sort a vector of 0,1,2's in ascending order. I thought the following two are equivalent:

void sortColors(vector<int>& nums) {
    int i=0,j=nums.size()-1;
    int k=0;
    while (k<=j){
        if (nums[k]==0){
            swap(nums[i],nums[k]);
            ++i;
            ++k;
        } 
        else if (nums[k]==1) {
            ++k;
        }
        else if (nums[k]==2){
            swap(nums[j],nums[k]);
            --j;
        }
    }
}

and

void sortColors(vector<int>& nums) {
    int i=0,j=nums.size()-1;
    int k=0;
    while (k<=j){
        if (nums[k]==0){
            swap(nums[i],nums[k]);
            ++i;
            ++k;
        }
        if (nums[k]==1) ++k;
        if (nums[k]==2){
            swap(nums[j],nums[k]);
            --j;
        }
    }
}

However, only the first is correct. When test running nums={2,0}, the first one does the correct ordering while the second function does nothing. What are the difference here?

Aucun commentaire:

Enregistrer un commentaire