Java Recursion

Derek Banas
9 Mar 201314:11

Summary

TLDRThis tutorial delves into the concept of recursion, explaining it as a method that calls itself, simplifying the problem with each call until it reaches a base case. The video demonstrates calculating triangular numbers and factorials using recursion, illustrating the process with visual examples and code snippets. Additionally, it provides a detailed walkthrough of the merge sort algorithm, showcasing its efficiency and organization through an animated execution, all aimed at helping viewers grasp these fundamental programming concepts.

Takeaways

  • 🔁 Recursion is a method where the function calls itself, simplifying the problem with each call until it reaches a base case where it no longer calls itself.
  • 📊 The script explains how to find triangular numbers using recursion, which involves summing numbers from 1 to n, where n is the position in the sequence.
  • 📚 The base case for the triangular number example is when the input number equals 1, at which point the method stops calling itself and returns 1.
  • 📈 Triangular numbers are demonstrated visually as numbers arranged in triangles, with the nth triangular number being the sum of the first n natural numbers.
  • 🤔 The tutorial also covers a non-recursive method for calculating triangular numbers, which is a simple iterative process summing numbers from 1 to n.
  • 📝 The script provides a step-by-step explanation of how to implement a recursive method to calculate triangular numbers, including printing intermediate results for clarity.
  • 🎲 Factorials are introduced as another example of a calculation that can be performed using recursion, with the base case being factorial of 1 equals 1.
  • 👉 The merge sort algorithm is explained, which uses recursion to sort arrays efficiently by dividing the array into smaller parts, sorting them, and then merging them back together.
  • 📉 The merge sort process is visualized through the script, showing how it compares and swaps elements to sort the array incrementally.
  • 💻 The tutorial includes code examples and comments to aid understanding of recursive methods, triangular numbers, factorials, and the merge sort algorithm.
  • 🔍 The script encourages viewers to look at the provided code, which is heavily commented, to understand the inner workings of the merge sort algorithm.

Q & A

  • What is the main topic of this tutorial?

    -The main topic of this tutorial is recursion, including its definition, how it works, and its applications in calculating triangular numbers, factorials, and in the merge sort algorithm.

  • What is a recursive method?

    -A recursive method is a method that calls itself, simplifying the problem with each call until it reaches a base case where it no longer calls itself.

  • What are triangular numbers and how are they related to recursion?

    -Triangular numbers are numbers that can be represented in a triangle pattern. They are related to recursion because the script demonstrates how to calculate them using a recursive method.

  • How is the nth triangular number calculated using recursion?

    -The nth triangular number is calculated using a recursive method that adds the sequence of numbers from 1 to n, with each recursive call reducing the number by one until it reaches the base case of 1.

  • What is the base case in a recursive method?

    -The base case in a recursive method is the condition that stops the recursion, typically when the problem is simplified enough that it no longer requires further recursive calls.

  • Can you explain the non-recursive approach to calculating triangular numbers?

    -The non-recursive approach to calculating triangular numbers involves summing the sequence of numbers from 1 up to the desired number, without using method calls to itself.

  • What is a factorial and how is it calculated using recursion?

    -A factorial is the product of an integer and all the integers below it. It is calculated using recursion by multiplying the number by the factorial of the number minus one, until the base case of 1 is reached.

  • What is the merge sort algorithm and how does it use recursion?

    -The merge sort algorithm is a sorting technique that divides the array into smaller parts, sorts them, and then merges them back together in the correct order. It uses recursion to repeatedly divide the array until each part is a single element or empty, and then merge them back in sorted order.

  • How does the merge sort algorithm sort an array?

    -The merge sort algorithm sorts an array by first dividing it into halves, sorting each half, and then merging the sorted halves back together. This process is done recursively until the entire array is sorted.

  • What is the significance of the merge sort algorithm in computer science?

    -The merge sort algorithm is significant in computer science because it is an efficient, stable, and comparison-based sorting algorithm with a time complexity of O(n log n), making it suitable for large datasets.

Outlines

00:00

🔁 Introduction to Recursion and Triangular Numbers

The video script introduces the concept of recursion, a method that calls itself to solve a problem by breaking it down into simpler instances. It uses the example of calculating the nth triangular number to illustrate recursion. The script explains that a recursive method will eventually reach a base case where it stops calling itself. The process of calculating triangular numbers recursively is demonstrated, showing how each method call simplifies the problem until reaching the base case. The script also provides a visual representation of triangular numbers and contrasts the recursive method with an iterative approach that doesn't use recursion.

05:01

📊 Recursive Calculation of Triangular and Factorial Numbers

This section of the script delves deeper into the recursive calculation of triangular numbers, providing a step-by-step breakdown of the process and the base case for the recursion. It then transitions into explaining how to calculate factorials using recursion, with a similar structure of a base case and recursive calls. The script includes code snippets and explanations to demonstrate the recursive process for both triangular numbers and factorials, highlighting the method's efficiency in breaking down complex problems into manageable parts.

10:02

🔍 Understanding the Merge Sort Algorithm Through Recursion

The final paragraph of the script shifts focus to the merge sort algorithm, which utilizes recursion to sort arrays efficiently. The script provides a high-level overview of how merge sort works, explaining the process of dividing the array into smaller parts, sorting them, and then merging them back together. The explanation includes a visual demonstration of the sorting process, showing how the algorithm compares and orders elements within the array. The script emphasizes the importance of understanding the underlying mechanics of merge sort, even if one typically uses pre-written code for such tasks.

Mindmap

Keywords

💡Recursion

Recursion refers to a method in programming where the function calls itself in order to solve a problem by breaking it down into simpler sub-problems. In the video, recursion is the central theme, with the presenter explaining how it works and demonstrating its use in calculating triangular numbers, factorials, and as a fundamental part of the merge sort algorithm. The script provides a clear example of a recursive method named 'get try number' that calculates the nth triangular number.

💡Triangular Numbers

Triangular numbers are a sequence of numbers where each number represents a triangle with dots, with the nth triangular number representing a triangle with n rows of dots, each row containing n dots. The script describes how to calculate these numbers using both iterative and recursive methods, with the recursive method being a key demonstration of recursion's utility.

💡Factorials

A factorial, denoted by an exclamation mark (e.g., 5!), is the product of all positive integers less than or equal to a given number. In the video, the presenter discusses how to calculate factorials using recursion, showing that the factorial of a number n is the product of n and the factorial of (n-1), with the base case being the factorial of 1 which is 1.

💡Merge Sort

Merge sort is a divide-and-conquer algorithm used for sorting arrays. The script explains that merge sort works by dividing the array into smaller parts, sorting those parts, and then merging them back together in the correct order. The presenter demonstrates the algorithm's process through a visual example, showing how it systematically organizes the array elements using recursion.

💡Base Case

In the context of recursion, the base case is the condition under which the recursive method stops calling itself and returns a value directly. The script illustrates this with examples where the base case is when the input number equals one, at which point the method does not call itself but returns a value, preventing infinite recursion.

💡Recursive Method

A recursive method is a function that includes a call to itself within its own body. The script provides an example of a recursive method named 'get triangular number', which calculates the nth triangular number by making recursive calls with decrementing values until it reaches the base case.

💡Divide and Conquer

Divide and conquer is a problem-solving strategy where a problem is divided into smaller sub-problems, each of which is solved independently, and the solutions are then combined to solve the original problem. The merge sort algorithm, as described in the script, is a classic example of this approach, where the array is repeatedly divided and then the sorted sub-arrays are merged.

💡Sorting Algorithm

A sorting algorithm is a set of instructions that converts a list of items into order. The script discusses different sorting algorithms, such as merge sort, and their applications, particularly focusing on how recursion can be used within these algorithms to achieve efficient sorting.

💡Recursive Call

A recursive call is when a function calls itself within its own execution. The script demonstrates this concept through the 'get factorial' method, where each call to the method results in another call with a decremented value until the base case is reached.

💡Iterative Method

An iterative method is a way of solving problems using loops that repeat a block of code until a certain condition is met. The script contrasts this with recursion by showing how triangular numbers can also be calculated iteratively without the use of recursion, using a loop to sum the numbers from 1 to n.

Highlights

Introduction to recursion, explaining it as a method that calls itself until a simpler problem is reached.

Demonstration of a recursive method to find the nth triangular number.

Explanation of triangular numbers and their visual representation as triangles.

Comparison between recursive and iterative methods for calculating triangular numbers.

Illustration of the base case in recursion as a condition to stop the method from calling itself.

Recursive method implementation for calculating triangular numbers with detailed tracing.

Introduction to factorials and their calculation using recursion.

Recursive method for calculating factorials, including base case and recursive case.

Visualization of the merge sort algorithm using recursion to sort an array.

Detailed explanation of how merge sort works step by step.

Commentary on the efficiency and organization of the merge sort algorithm.

Demonstration of the merge sort algorithm in action, sorting an array.

Explanation of the sorting process within merge sort, including shifting and comparing elements.

Final sorting of the array using merge sort, showcasing the algorithm's effectiveness.

Invitation for viewers to leave questions or comments for further discussion.

Teaser for the next tutorial covering more sorting algorithms.

Transcripts

play00:00

whoa Internet and welcome to part 6 of

play00:02

my job algorithms tutorial today I'm

play00:03

going to talk about recursion what it is

play00:06

how it works and on top of that we're

play00:08

going to take a look at what our

play00:09

triangular numbers water factorials and

play00:11

how to use recursion in the merge sort

play00:14

all of the tutorials in my java

play00:16

algorithms tutorial series is available

play00:18

and i'll link in the upper right-hand

play00:20

corner if you want to look at something

play00:21

else i have a lot to do so let's get

play00:23

into it so what exactly is recursive

play00:25

method it's just a method that calls

play00:27

itself and with each method call the

play00:30

problem is going to become simpler and

play00:32

simpler and the only condition with a

play00:34

recursive method is that it will

play00:36

eventually lead to a point where the

play00:39

method no longer calls itself so let's

play00:42

see exactly what that looks like

play00:44

over here on the right-hand side of the

play00:46

screen you will see a recursive method

play00:48

and it is named get try number and if

play00:51

you pass in a value like 6 into this guy

play00:54

well obviously 6 is not equal to 1 so we

play00:57

skip over this condition we get down

play00:59

here where num is going to be equal to 6

play01:01

of course and then we have a call to the

play01:03

method itself and it is going to pass in

play01:06

8 5 whenever that happens again you have

play01:08

a situation where you do not know what

play01:10

this is but you know what this is equal

play01:12

to and that is again going to be 5 and

play01:15

you're going to pass in 4 then you get a

play01:17

situation where you have 4 plus whatever

play01:20

the result of this calculation and then

play01:23

you have 3 plus whatever 3 minus 1 equal

play01:27

to 2 and the 2 goes back into the method

play01:29

again and then as we approach the end

play01:32

you see that 2 plus get try number and

play01:35

we are passing a one end and whenever

play01:37

you look at this guy up here you can see

play01:39

that we are getting to the end and the

play01:42

number 1 is passed in just as you can

play01:44

see here it goes up here then we can now

play01:47

calculate the previous method 2 plus 1

play01:50

is going to be equal to 3 now we'll that

play01:51

we have a result for that we can pass

play01:52

that up here now that we have a result

play01:54

for this guy we can pass the 6 up here

play01:56

now that we have a result for that we

play01:58

can pass the 10 up here and now that we

play02:00

have a result for this we can pass the

play02:02

15 up there and that is how recursion

play02:06

would work if you're trying to find the

play02:07

nth triangular number if you don't know

play02:10

what a triangular number is

play02:11

don't worry I'm going to cover that in a

play02:12

second so let's look at recursion using

play02:15

a totally different layout if that

play02:17

didn't solidify it in your mind right

play02:19

here I have three methods and they are

play02:22

all inside of boxes because this is our

play02:24

recursion works so let's say a 3 is

play02:27

passed into my recursive method again we

play02:29

get to a situation where we do not know

play02:32

what the value is after this calculation

play02:35

is done hence all of these methods are

play02:38

going to be calling down to these guys

play02:40

until we get to the part right here

play02:43

where 1 minus 1 is going to be equal to

play02:45

0 and this is going to return a value of

play02:47

1 as it did right there now that we have

play02:50

returned value we can now take this one

play02:52

and pass it up here and that's exactly

play02:54

what we did and now we know that 2 plus

play02:56

1 is going to be equal to 3 just as you

play02:59

see right there and now we can return a

play03:02

3 up here and whenever we do that 3 plus

play03:05

3 is going to be equal to 6 and all of

play03:09

our method calls or done so there's two

play03:12

different ways to look at recursion now

play03:13

let's look at it using code so here is

play03:16

our code and all the code here both that

play03:18

I show you as well as the code that I

play03:20

don't show is available in a link in the

play03:22

description under the video so what I'm

play03:23

going to do here first off is to show

play03:25

you what triangular numbers are and I'm

play03:29

just going to come in here and go

play03:30

recursion tool and then I'm going to

play03:33

calculate and print out triangular

play03:36

numbers so let's say I want to do it up

play03:37

to the sixth triangular number I'll save

play03:40

that and execute now you know what a

play03:42

triangular number is the first one

play03:44

doesn't look much like a triangle but

play03:46

you can see that the second one most

play03:48

definitely does and all that we're doing

play03:50

here is going one two and three and

play03:53

finding the triangular number then once

play03:56

again we are finding the third

play03:57

triangular number by going one two three

play04:01

four five six and again there is the

play04:05

third triangular number and you can see

play04:07

that there is going to be a equal number

play04:09

of rows to ultimate columns that's why

play04:13

it looks like a triangle and that's why

play04:14

it is called triangular numbers so now

play04:16

before I show you how to create

play04:18

triangular numbers or calculate

play04:20

triangular numbers using recursion I'm

play04:22

going to show you how to do it not using

play04:23

recursion because

play04:24

is even though triangular numbers and

play04:27

recursion or normally talk together

play04:29

it ultimately doesn't make sense to use

play04:31

recursion when calculating triangular

play04:34

numbers but don't worry about it

play04:35

and you can forget that I just said that

play04:37

just focus on the recursion part this is

play04:39

how you would calculate triangular

play04:41

numbers if you didn't want to use

play04:43

recursion pretty simple so I can just go

play04:45

angular number is equal to zero and how

play04:49

you actually calculate a triangular

play04:50

number is let's say you wanted to find

play04:52

the third triangular number you would

play04:54

just go three plus two plus one and get

play04:57

six

play04:58

that is the third triangular number and

play05:01

that's how they're calculated so now

play05:02

knowing that what we're going to do is

play05:04

go while number is greater than zero

play05:07

we're going to calculate our triangular

play05:09

numbers by decrementing backwards from

play05:12

r3 so triangular number is going to be

play05:15

equal to triangular number plus number

play05:18

and then we are going to decrement

play05:19

backwards from that and then after this

play05:21

we're gonna go return triangular number

play05:23

and if we jump back up into main and see

play05:26

how easy it is to print that out

play05:27

we're gonna go recursion tool throw that

play05:29

in there and get triangular number and

play05:32

we can throw a six inside of there and

play05:33

let's just block this out so it's not

play05:36

confusing and go in here and put TN just

play05:39

to give a little bit of information and

play05:40

execute and there you can see triangular

play05:42

number is going to be equal to 21 21 is

play05:46

the sixth triangular number so now let's

play05:49

take a look at how to calculate or find

play05:51

triangular numbers using recursion I'm

play05:53

actually going to put a couple things

play05:55

inside of this so that we're going to be

play05:58

able to easily see what's going on as

play06:01

recursion is occurring so we're going to

play06:03

go pass in our number just like we did

play06:05

before and just to reiterate every

play06:08

recursive method is going to have a

play06:10

condition that leads to the method no

play06:13

longer making another call on itself and

play06:15

that condition is known as the base case

play06:18

so in this situation it's going to be

play06:20

number equal to one and the other

play06:23

example I show you is going to be very

play06:24

very similar but because I want to show

play06:26

you exactly what is going on here which

play06:28

method is going to be entered inside of

play06:31

this I'm going to put number right there

play06:32

and here I'm going to put the value that

play06:36

is going to be returned and then of

play06:37

course

play06:38

going to return that value and then

play06:39

we're going to get into this situation

play06:41

where a 1 was not entered in that

play06:44

situation we're going to calculate a

play06:46

result which is going to be number plus

play06:49

and this is going to be the method call

play06:51

back to itself right like that and of

play06:53

course we're going to pass whatever the

play06:55

number is minus 1 into that guy to get

play06:58

the result then so then I can just print

play07:01

some information here on the screen so

play07:02

you can see what's going on I'm going to

play07:04

come in here and type in result so

play07:06

result will get printed out on the

play07:07

screen and I'm going to get rid of this

play07:09

because I'm going to put some additional

play07:11

information inside of here and that

play07:13

additional information is going to be

play07:14

the actual method that is going to be

play07:17

executed and here I'm just going to go

play07:19

get TN just to be simple plus you'll see

play07:22

what this looks like in a second and

play07:23

then of course we're going to return our

play07:25

result and then if we bounce up here

play07:27

let's copy this first and get to this

play07:30

guy right here Chaney I can actually

play07:32

just change that to R and execute it

play07:34

you're going to see exactly what goes on

play07:36

when these triangular numbers are

play07:37

executed again we're going to enter

play07:39

method 6 enter method 5 4 3 2 1 1 is

play07:44

going to get a return value which is

play07:46

going to be equal to 1 2 plus 1 is going

play07:49

to be equal to 3 and 3 plus 3 is going

play07:52

to be equal to 6 and 4 plus 6 is going

play07:55

to be equal to 10 and 5 plus 10 is going

play07:57

to be equal to 15 and 6 plus 15 is

play08:01

finally going to be equal to 21 and we

play08:04

know now what the sixth triangular

play08:06

number is using recursion and you can

play08:09

see exactly right there exactly how it's

play08:11

calculated so now let's take a look at

play08:13

how to calculate factorials in much the

play08:15

same way so I'm going to scroll down

play08:17

inside of here and of course the

play08:19

factorial of 3 is going to be calculated

play08:22

3 times 2 times 1 that is or a factorial

play08:28

which of course is going to be equal to

play08:29

6 so now we have to actually come in

play08:32

here and calculate that and of course

play08:34

I'm going to use recursion so I'm going

play08:36

to go public int get factorial it's

play08:39

going to receive a number and of course

play08:41

I'm going to put a little note inside of

play08:43

here so you can see exactly how the

play08:45

method is going to be entered and so

play08:47

forth and so on and then we're going to

play08:49

put our base case inside of here

play08:51

equal to one again we're going to be

play08:53

doing a very very similar thing return

play08:55

one and then of course we're going to

play08:57

have one return and then of course we're

play08:59

going to go else calculate the result

play09:02

which is going to be number times get

play09:04

back toriel call to itself it's going to

play09:07

pass in number minus one system out

play09:10

returns and this is going to be the

play09:12

result of the calculation and then let's

play09:14

jump up here and actually copy this so I

play09:16

don't have to actually type all that out

play09:18

again because like I said very very

play09:19

similar and change this to print paste

play09:22

that in there and here it's going to be

play09:24

factorial then the difference is going

play09:26

to be this is going to be a

play09:27

multiplication sign and then of course

play09:28

after we're done messing around with

play09:31

that we can actually calculate and

play09:33

return our result

play09:34

now get factorial jump abeer factorial

play09:37

throw this inside of there I'll save and

play09:39

execute and there you can see exactly

play09:40

how factorials are calculated just

play09:42

exactly the same method six method of

play09:44

five method for method three method to

play09:47

method one method one is going to return

play09:49

1 2 times 1 is going to be equal to 2

play09:51

and 3 times 2 is going to be equal to 6

play09:54

and 3 times 4 is going to be equal to 24

play09:56

and so on and so on and so on so there

play09:58

are two more examples of how to use

play10:01

recursion to make calculations and do

play10:04

all kinds of funky stuff now rather than

play10:06

type out a whole bunch of information

play10:07

about the merge sort I'm going to

play10:09

instead show you precisely how it works

play10:12

now the merge sort is going to sort in a

play10:16

very very neat and organized way very

play10:19

very fast as well and of course it's

play10:21

going to use recursion to do so now I

play10:24

could have went through here and typed

play10:26

out all of this code but instead I just

play10:28

went in and heavily commented it and

play10:29

decided to focus all of my time in this

play10:32

part of the tutorial to actually showing

play10:33

you the merge sort work because most of

play10:36

the time you're just going to simply

play10:38

copy and paste and execute a merge sort

play10:40

you're not going to try to memorize it

play10:42

but it is important understand how it

play10:43

works so let's execute this guy ok so

play10:45

you can see here this is the start of

play10:48

our array and these are the indexes and

play10:50

then these are the values that are going

play10:51

to be stored inside of them well let's

play10:53

just look at exactly what is going on as

play10:55

we are going down through this we're

play10:58

going to hit apart where we are going to

play11:00

judge the differences between index 0

play11:03

and 1 and as you can see

play11:05

here we're checking to see if 10 is less

play11:08

than 8 of course it's not so what we're

play11:10

going to do with the merge sort is we're

play11:12

going to store the value of 8 in a

play11:14

temporary variable we are then going to

play11:16

take the value that is stored in the 0

play11:19

index which is 10 and instead store it

play11:22

in the 1 index

play11:23

why because we are then going to copy 8

play11:26

which was stored in temp into the zero

play11:29

index and as we come down here you can

play11:32

see that is precisely what happened they

play11:35

switched places and as we continue

play11:36

onwards you can see that it's then going

play11:39

to judge the differences between what is

play11:42

in index 2 and 3 see it's slowly going

play11:45

through this array and sorting it bit by

play11:48

bit

play11:48

so it's going to say is 4 less than 80

play11:51

of course hence we have nothing left to

play11:53

do so now we have the first two indexes

play11:56

sorted and the second grouping of index

play11:59

is sorted so now what we need to do is

play12:01

sort all four of these and that's

play12:04

exactly how them the merge sort works so

play12:06

if we move onwards we're going to be

play12:08

checking if 8 is less than 4 since that

play12:12

comes back false what are we going to do

play12:14

we're going to store four in a temporary

play12:16

variable and because we already know

play12:17

that 8 is less than the value that is in

play12:20

stored inside of index 1 we can move 4

play12:23

down to here and that is precisely what

play12:26

we do just by shifting these indexes

play12:28

along until we get to the part right

play12:31

down here and you can also see I have a

play12:33

whole bunch of information on the screen

play12:34

in addition to what I'm actually talking

play12:36

about to help you along if you wanted to

play12:37

do this on your own you can see that the

play12:39

flora gets shifted there and the 8 and

play12:41

10 get moved up next we're going to

play12:43

check if this index is less than this

play12:45

index which it isn't and then finally we

play12:48

are going to check if 10 is less than 80

play12:51

which of course it is and you can see

play12:53

once we get to this part that the first

play12:55

part the first 4 rather than the first 2

play12:58

are all going to be in proper order then

play13:01

what the merge sort does is focuses on

play13:03

this second part and sorts it as you're

play13:06

going to see we're going through here

play13:08

we're going to be moving the 1 into this

play13:11

position which is exactly what happens

play13:13

there and then we're going to be moving

play13:15

the 3 into the 13 position which is

play13:18

actually what we are going to do right

play13:20

here and then of course finally we're

play13:22

going to sort this second part to move

play13:24

the 11 where the 13 is and that's what

play13:26

we did right there once again these two

play13:28

are in order and these two are in order

play13:30

so now we have to get all of those in

play13:33

perfect order all four of them and we're

play13:35

going to move onwards and take all of

play13:37

these array parts and move them in order

play13:40

by shifting just as we did previously

play13:42

until the whole entire array is sorted

play13:45

and in perfect order

play13:48

so that is a run-through quickly of how

play13:50

the merge sort works once again I have

play13:53

all the code and it's heavily heavily

play13:54

commented for the merge sort if you want

play13:56

to take a look at it and I thought it

play13:57

would be interesting to look at it as it

play13:59

was being executed like this rather than

play14:01

just going line by line by line of code

play14:03

please leave any questions or comments

play14:05

below up next I'm going to cover some

play14:07

more sorting algorithms otherwise till

play14:10

next time

Rate This

5.0 / 5 (0 votes)

Ähnliche Tags
RecursionJavaAlgorithmsTriangular NumbersFactorialsMerge SortCoding TutorialRecursive MethodSorting AlgorithmComputer Science
Benötigen Sie eine Zusammenfassung auf Englisch?