2

Step one and step two (step three) seem like repeatedly running to me. Why is it programmed like this?

    int i = 0, j = 0; 
    int k = l; 
    while (i < n1 && j < n2) {     ----step one
        if (L[i] <= R[j]){ 
            arr[k] = L[i]; 
            i++; 
        } 
        else{ 
            arr[k] = R[j]; 
            j++; 
        } 
        k++; 
    } 
    while (i < n1){             ---step two
        arr[k] = L[i]; 
        i++; 
        k++; 
    } 
    while (j < n2){         ----step three
        arr[k] = R[j]; 
        j++; 
        k++; 
    } 
}
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
TIGUZI
  • 231
  • 1
  • 3
  • 12
  • This code is just doing the merge step, merging arrays L and R into arr. Step 2 and 3 are adding the remaining numbers, only one of the 2 will ever be executed, this is after the end of L or R was reached, to fill in the remaining values of the other array. – maraca Nov 02 '19 at 22:19

2 Answers2

2

"Step one" does the work of merging from two source arrays into the destination. When L or R is exhausted there may still be unmerged elements remaining in the other source array. "Step two" exists to copy any remaining elements from L to the destination. "Step three" serves the same purpose for R.

Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
0

You can choose to skip those steps and just use a for loop, if that is easier for you in the following way:

        for(int i = 0; i < arr.size(); i++) {
            if(r >= right.size() || (l < left.size() && left[l] < right[r])) {
                arr[i] = left[l++];
            } else {
                arr[i] = right[r++];
            }
        }
arr.size() = n1 + n2 in your implementation

or even this:

while(len--) {
            if(r >= right.size() || (l < left.size() && left[l] < right[r])) {
                arr[i] = left[l++];
            } else {
                arr[i] = right[r++];
            }
}
where len = n1 + n2

I personally find this way more readable and easier, but to each their own! (this is unstable and can be made stable, but I leave that part for the reader to figure out!)

edit: I noticed it's java, maybe len-- won't work you can do len >= 0 and len-- inside the loop.

Xgh05t
  • 230
  • 2
  • 11