알고리즘 S1: Recursion (재귀)

소바·2022년 9월 21일
0

recursion




Recursion 은 stack 자료구조를 이용하기 때문에 함수를 종료 시키는 condition을 명시하지 않으면 무한으로 자기자신을 호출하면서 stack이 쌓이다가 메모리 depth 초과로 오류가 발생한다.

Call stack

Fatorial

값을 return하면서 함수를 종료하기 이전에 다시 자기자신 function이 호출되면서 callstack 에 return 해야하는 값이 쌓이게 된다
n=1 이라는 condition이 true 가되면서 function 호출이 끝나면(Recursion) 쌓인 function들이 차례로 값을 return하면서 pop 된다.

Bubble sort

I'll highlight that an orange and we're going to compare the first item with the second item.
We're going to switch them now, we're going to compare the second item with the third item, and if

And we're going to say function bubbles sort and we're going to pass it, the array that we're going to sort in as we discuss in the last video, this is obviously going to be a for loop inside of a for
So we're going to set I equal to the length minus one.

while loop

for loop

Now a for loop works similarly to a while loop, but instead of testing a condition, we’re specifying the
number of times that we want the loop to run. And the syntax looks something like this.

you can see that the for loop is essentially just a reshuffling of all the elements of the while loop.
So we're changing the while keyword to the for keyword, and then the var creation goes into the parentheses, defining the starting point,
so we're starting from 1. Then the next thing inside the parentheses is the ending point of the for loop, so we'll end once i is less than 2.
And finally, if we're using the while loop, we have to include the code that changes i inside the while
Now it's integrated into the declaration for the for loop so that when we create the for loop we already define the starting point, the ending point,

while loop -> for loop
the parentheses, we first declare the variable that we're going to use to count.
So we can cut that from there and paste it here instead.
So now, inside the for loop, we're creating a counter, called count, starting point from 1 and ends at
The next thing that we have to add is how are we going to change the counter.
Now of course you can decrease it by 1 each time as well,
And this would work, say for example, if you're counting down from 100 to 1.

So the for loop is really flexible like that and allows you to count in any direction and increase
your count by 2 or by 3 or by any number you wish really.

Now a lot of students wonder in which cases do I use the while loop and in which cases should I use

Keep in mind that while is essentially checking for a state, so it's while something is true,

And essentially you want to repeatedly run an instruction while the program is in a certain state. But

for the full loop you're essentially trying to iterate.
You're trying to run a piece of code many many times and you're going to use the for loop to define

profile
소바보이

0개의 댓글