0% found this document useful (0 votes)
2 views15 pages

CS50 Week - 03 - Algorithms

The document outlines various algorithms covered in CS50's Week 3 lecture, including linear search, binary search, bubble sort, selection sort, and merge sort, along with their complexities. It also discusses recursion and provides examples such as the factorial function and the Collatz conjecture. The lecture emphasizes the importance of understanding algorithm efficiency and the recursive approach in programming.

Uploaded by

Armaan Ahuja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

CS50 Week - 03 - Algorithms

The document outlines various algorithms covered in CS50's Week 3 lecture, including linear search, binary search, bubble sort, selection sort, and merge sort, along with their complexities. It also discusses recursion and provides examples such as the factorial function and the Collatz conjecture. The lecture emphasizes the importance of understanding algorithm efficiency and the recursive approach in programming.

Uploaded by

Armaan Ahuja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 15
CS50: Week-03 - Algorithms Lecture times Binary: n/2 pa Cea Cet es If 5@ is behind doors[middle] potest Seta Ra CrCl] nee ee Ce Ce al wer Else if 50 > doors[middle] rei CC BeginnersBook.com Complexity > include include Ant eain(void) « int nurbers{] = {28, 508, -10, 5, 108, 1, -5@); nt n= get_ine(*Nusber: "); for (int 1 = 0; 4 < 75 44) « A (nuebers[i] == 9) ‘ print#("Found\n") ) ) peinté(*not foune\ > successfully without IC programming, return Oat the end of the main(function signifies thatthe program has execu Here's a breakdown: returnstatement:This statement terminates the execution of a function and returns control to the calling function value:By convention, a return value of O indicates successful execution. + Operating System:The operating system can use the retum value to determine the exit status of the program.This can be useful for scripting ancl automation purposes. In, return 3 signifies thatthe function is exiting and returning the value 1 to the calling functor operating Data Structures Aa See Salad { te Md be Cella } Pata dot operator (.) is used to access members ofa structure or union. I's algo known as the direct member access Tira PULea et) Pe CES eee cee a) ese eee Pt CS eee Se es Seu ee PO CUE (CeCe ae Ate anlage) CS SPL eC) et Sa a UR CCS oe printf("Not found\n"); rata sere Paes Peers Section-3 Factorial 1!=1 21 s1 *2 Ble1*2*3 Recursion 4: =1*2*3*4 Factorial Factorial 4! =4* 3! (4) 31 = 3 * 2! 4 * £(3) 3 * £(2) 2)=2* 1! 2 * £(1) a!=1 1 * £(@) Factorial #(4) SS 4 4*6 Shorts: Linear Search 6 Linear Search PUESUE METS EMICHETAE?) EMEC) In pseudocode: Repeat, starting atthe first element: aha fst elements what you'r ning for (the target), sop. Other, mows tthe nek slment. Shorts: Binary Search Binary Search + In binary search, the idea of the algorithm is to divide and conquer, raducing the search area by half each time, trying tofind a target number. + Inger to leverage tis poner however ur ey mst at besarte, ee \aecsot make suimpton abou th says samt Binary Search tn pseudocode: + Repeat until the (subjarray is of size 0: + Calculate the middle point ofthe current (sublareay. + if the targets atthe mide, stop, + Otherwise, the target is ess than what's at the middle, repeat, ‘hanging the end point io be jst tothe let ofthe mile + Otherwise ifthe target is greater than what’ atthe middle, fepeat, changing the start point to be just to the right of the ile Binary Search » 8 In pseudocode: Repeat until the (sub)arrayis af sie 0: Cleslte mice ptf secre ev) ithe targets the mild op Dither the ogee than what's atthe mid, repeat changing the en ins tobe stot ote me. theres, he ages rater than what's hemi, repeat changing the tart puinc tobe usttothe igh othe mid, Binary Search Ollog n) (2) Bubble Sort Bubble Sort + In bubble sort, the idea of the algorithm isto move higher valued elements generally towards the tight and lower value elements generally towards the lett. Inpseudocade: 1 Ser wap counter to a non-zero value + Repest unt the swap counter eO + Leokac each ads ar Bubble Sort In pseudocod: ‘Set swap counter to a non-2er0 value Repeat until the swap counter Is 0: Reset snap counter to0 } Look at each adjacent pair Big © (0) and Big Omega (0) are notations used to describe Cee nee ea Lok ond Worst-case performance, while Big Omega describes the eee acs Bubble Sort * Worst-case scenario: The array isin reverse order; we have ‘to "bubble" each of the n elements all the way across the array, and since we can only fully bubble one element into position per pass, we must do this n times. + Best-case scenario: The array is already perfectly sorted, and we make no swaps on the first pass. Selection Sort Selection Sort + Worst-case scenario: We have to iterate over each of the n elements of the array (to find the smallest unsorted element) and we must repeat this process n times, since only ‘one element gets sorted on each pass. * Best-case scenario: Exactly the samel There's no way to guarantee the array is sorted until we go through this Process forall the elements. Selection Sort O(n?) Qn?) Recursion © hutps://youtube/DASWe62eITEMeature=shared Recursion + We might describe an implementation of an algorithm as being particularly “elegant” if it solves a problem in a way that is. both interesting and easy to visualize. + The technique of recursion is a very common way to implement such an “elegant” solution. * The definition of a recursive function Is one that, as part ofits ‘execution, invokes itself. Recursion “= The factorial function (is defined over all positive integers. + nl equals all of the positive integers less than or equal to n, multiplied together. + Thinking in terms of programming, we'lldefine the mathematical function nl as fact (n). Recursion fact(1) = 1 fact(2) = 2% 1 fact(3) =3 "2°21 fact(4)= 443 *2*2 fact(S)=5*4*3 "241 Recursion + This forms the basis for a recursive definition of the factorial function. + Every recursive function has two cases that could apply, given any input * The base case, which when triggered wil terminate the recursive process. +The recursive ese, which is where the recursion will actually occur 10 Recursion int Fact(int n) ( sf (nee 2) return 33 ) 1) recursive case , return n 7 fact(n-2); Recursion Ant fact (int n) C 11 base case U1 recursive case , Recursion int fact(int n) C Af (n =e 1) { return 2; » else { } y Recursion + Im general, but not always, recursive functions replace loops in rnon-recursive functions, int fact(int 9) return © Fact(n-t)s Recursion nt fact2Cint n) t Aint product wunile(n > 8) t product *= nz i= return product + + Multiple base cases: The Fibonacci number sequence is defined as follows: + The frst element i 0, + The second element is 2. * The ni elements the sum ofthe (n-1)" and (r-2) elements. + Multiple recursive cases: The Collatz conjecture. it Recursion + The Collatz conjecture is applies to positive integers and speculates that it is always possible to get "back to 1” if you follow these steps: + if nis stop. + Otherwise, ifmis even, repeat this process on n/2. + Otherwise, fms odd, repeat tis process on n+ 1. + Write 2 recursive function collatz(n) that calculates how many steps it takes to get to 1 if you start from n and recurs as indicated above. Recursion 2 4 aa 11 sates 9694949293 4 2 aaa $$ Sa4edeoeoa98 § Garp Wasa tanzeo2 91 2% 99919329919 9092091095909HIE EI 8 3 abaaads ts spas a9 sedasa9e ih WansaamI> 91949994 Sodas prea 94deI24 Recursion tne comatztie 11 base case #@=D 17 evan nonbers hse $€ ((0 8 2) me 8 return + colhet(n/2); 11 066 rumvars return 1+ collatz(3"9 6 195 ? Merge Sort 12 Merge Sort + In merge sort, the idea of the algorithm is to sort smaller arrays and then combine those arrays together (merge them) in sorted order. + Merge sort leverages something called recursion, which we'll touch on in more detail in a future video. In pseudocode: * Sort the left hal of the array (assuming n> 1) + Sort the right haif of the array (assuming n > 1) + Merge the two halves together Merge Sort * Worst-case scenario: We have to split n elements up and then recombine them, effectively doubling the sorted subarrays as we build them up. (combining sorted 1-element arrays into 2-element arrays, combining sorted 2-element arrays into 4-element arrays...) * Best-case scenario: The array is already perfectly sorted. But ‘we still have to split and recombine it back together with this algorithm. 1B Merge Sort O(n fog n) Q{n fog n) ane (6? 6 Saar eps FERS AES es 12 3 wees n&ewo w = 15

You might also like