r/learnprogramming • • 16d ago

help me understand recursion/mergesort

hello can anyone help me with this problem, i have issues understanding the logic

int sumPart(int[] a, int start, int end) {

if (end - start == 1) {

return a[start];

}

int mid = (start + end) / 2;

int left = sumPart(a, start, mid);

int right = sumPart(a, mid, end);

return left + right;

}

2 Upvotes

10 comments sorted by

•

u/AutoModerator 16d ago

To all following commenters: please, do not bring up the old circlejerk jokes/memes about recursion ("Understanding recursion...", "This is recursion...", etc.). We've all heard them n+2 too many times.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

2

u/edwbuck 16d ago

There are many ways to solve a problem. Recursion is simply, "how do I partially solve it, making it into a smaller problem, in a way that is guaranteed to eventually solve it."

Mergesort can be implemented with recursion, but it can also be implemented without recursion. It's just easier to implement it with recursion if you defined merge sort as:

  1. How do I reduce the size of groups of items, so they are easier to sort.

The answer then becomes, split the list into smaller lists. Once a list is zero or one elements long, it's so easy to sort, you don't even have to do anything, it's already sorted.

2. Now you have thousands of tiny lists, how do you combine them into larger sorted lists?

For each two lists, walk them in their sorted order, building a combined list of all the elements in sorted order. Stop when you have only one list.

That's mergesort in a nutshell. How you implement it is up to you, but you should see how it can naturally follow recursion patterns of solving problems, even if you choose to write a merge sort that isn't using classical function recursion.

1

u/Intelligent_Gur8280 16d ago

It helps to say what the function promises: sumPart(a, start, end) returns the sum of the elements from index start up to, but not including, end. Base case: if the range has exactly one element, that element is the sum. Otherwise split the range at mid, trust that each half returns the correct sum for its own half, and add the two results. Trace it with a = {3, 1, 4, 2}: sumPart(0,4) has mid = 2, so left = sumPart(0,2) and right = sumPart(2,4). sumPart(0,2) splits into sumPart(0,1) = 3 and sumPart(1,2) = 1, so it returns 4. sumPart(2,4) splits into 4 and 2, so it returns 6. The final answer is 4 + 6 = 10. Mergesort uses the same shape: split in half, solve each half, then combine (merge instead of add).

1

u/Recycled5000 16d ago edited 3d ago

https://www.geeksforgeeks.org/dsa/start-end-start2-preferrable-method-calculating-middle-array-start-end2/

The expression (start + end)/2 is subject to overflow (when done in a fixed sized int), even though the division would bring the value back into a representable range, the damage by overflow, when it happens, isn’t corrected by the division. Overflow is fundamental loss of information, here the most significant part of the value, so, total corruption (not like a rounding error). (As an example, in overflow, what should be positive numbers can become negative, so clearly a division by 2 will not fix that as the result will stay negative.)

Hence the alternative way of coding that.

1

u/jjangg96 16d ago

the thing to notice is that the range is half open, start is included and end is not. that's why the base case is end - start == 1, it means the range has exactly one element in it.

say a is {100, 101, 102, 103, 104}. first call is (0, 5), mid is 2, so it calls (0, 2) and (2, 5). (0, 2) splits into (0, 1) and (1, 2), both single elements so they return 100 and 101. (2, 5) splits into (2, 3) and (3, 5), and (3, 5) splits again into (3, 4) and (4, 5).

nothing gets added on the way down. the left + right only happens as the calls start returning, so 100 + 101, then 103 + 104, then 102 + that, then everything together.

mergesort has the same shape, it splits at mid and recurses on both halves. the only difference is that on the way back up it merges two sorted halves instead of adding two numbers.

1

u/Temporary_Pie2733 13d ago

It’s just parenthesization. For example, 1 + 2 + 3 + 4 = (1 + 2) + (3 + 4) = ((1) + (2)) + ((3) + (4)) = (1 + 2) + (3 + 4) = 3 + 7 = 10. Making a recursive call adds parentheses; returning from the call replaces  the sum with the answer and discards the parentheses. 

2

u/[deleted] 16d ago

[removed] — view removed comment

2

u/c77u77 16d ago
int sumPart(int[] a, int start, int end) {

    if (end - start == 1) {
        return a[start];
    }

    int mid = (start + end) / 2;

    int left = sumPart(a, start, mid);
    int right = sumPart(a, mid, end);

    return left + right;
}

3

u/pixel293 16d ago

What I think you should do is do this on paper. Create a list of 5 integers, maybe 100 to 104 and calculate what mid, left, right, and the return values is for each call to sumPart().

1

u/captainAwesomePants 16d ago

This code is an example of how to solve a problem by breaking it into parts. Its goal is to add up all of the numbers in a list. There are many ways to do such a thing. Here's an example:

int sumInOrder(int[] a) {
  int total = 0;
  for (int index=0; index < a.size(); index++) {
      total += a[index];
  }
  return total;
}

Your code, instead of doing it in order, instead breaks the list into two halves (left and right) and solves those recursively, then it returns the sum of the left and right sides of the list.

This is a perfectly valid but somewhat silly way to add things together, so I'm guessing that this is part of an explanation into sorting. After you understand how you could use this technique to add up all of the numbers, they'll probably explain how to use a similar technique to sort things instead.

I also recommend trying this out by hand on paper to watch it work.