ENG1003 Lecture Notes - Lecture 10: Binary Search Algorithm, Merge Sort, Big O Notation
!"#$%&'() !"#"$%&'%$"()"'*$+&,-+'(*$ +("$(./%"#"0&(1.%2 (&"0&(3,-%"#"0#&+'-,.#&"
(,+-(2%
456"-(20,+%&"$7$+%2",$%3"+("-(*+&(."%.%/#+(&"1%8#/'(,&
97$+%2"8#$"*("'*+&'*$'-":*(;.%35%"()"#*"%.%/#+(&
○
<.."-(*+&(.".(5'-"2,$+"1%"$0%-')'%3"#$"#*"#.5(&'+82
○
=
>8%&%"#&%"/#&'(,$"$+&#+%5'%$ +8#+"0&(3,-%"?1%++%&?"&%$,.+$"5'/%*"$(2%"
3%$'&%3"-&'+%&'#
=
*$%'&+# !"5((3")(&"3'$-,$$'*5"%))'-'%*-7 ()"#.5(&'+82$")&2"#"0&#-+'-#."
0%&$0%-+'/%
@(*-%0+,#..7"$'20.%"1,+"2#*7"3'))%&%*+"#00&(#-8%$
=
*,",-'&$+./$%'
!"0&(5&%$$'/%.7"1,'.3'*5"#".'$+"()"%.%2%*+$"'*"$(&+%3"(&3%&"ABBC"D
>("#33 %#-8"*%;"%.%2%*+E"$%.%-+$".(;%$+ /#.,%")&2"&%2#'*'*5"
,*$(&+%3 .'$+"#*3"$;#0$ +8'$"'*+("0.#-%
=
0+/,%'&$+./$%' !"F,$+".':%"#&&#*5'*5"0(:%&"-#&3$"'*"8#*3"BBC"$+&#'58+#;#7
G*/(./%$"$8')+'*5"()"%.%2%*+$"+("2#:%"&((2")(&"*%;
12&-3/$%' !"H#/#9-&'0+"1,'.+B'*"Array.sort() 2%+8(3"Bfaster+8#*"
$%.%-+'(*"$(&+I
4,%5$%)6+-,.7$)86%&/$+
!"17"2#:'*5"#"H#/#9-&'0+"+%$+"8#&*%$$"+("2%#$,&%"+8%"+'2% +#:%*"17"%#-8"
#.5(&'+82"+("$(&+"+8%"$#2%"3#+#$%+
*,",-'&+# 6+.!"#$%&'()
J&#-+'-#."$0%%3 K,$,#..7"0&'2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8%"$O,#&%"()"$'X%"()"'*0,+
V,+%&".((0".((:$"#+"%/%&7"%.%2"()"#&
§
a(&"%#-8"()"+8($%E"'**%&".((0".((:$"#+"#.."&%2#'*'*5"%.%2$"()"
#&
§
○
456"$%.%-+'(*"$(&+"-(3%"BBC"0%&)(&2$"$.(;%&"+8#*"M,'-:$(&+"1-($"()"
+8'$
○
A'*%#&'+82'-"+'2%"'$"$(2%;8%&%"1+;*"A'*%#&"S"M,#3&#+'-"+'2%
○
Week$10:$Algos$&$Efficiency
9#+,&3#7E"c"d#7"TeQf
QgPgh
Document Summary
Algorithm = a series of instructions to solve a problem or produce a particular outcome. Eg. computer system used to control elevator behaviour. System has no intrinsic knowledge of an elevator. All control logic must be specified as an algorithm. There are various strategies that produce better results given some desired criteria. Sorting = good for discussing efficiency of algorithms frm a practical perspective. = progressively building a list of elements in sorted order l--> r. To add each new element, selects lowest value frm remaining unsorted list and swaps this into place. Insertion sort = just like arranging poker cards in hand --> straightaway. Involves shifting of elements to make room for new. Quicksort = javascript built-in array. sort() method - faster than selection sort! = by making a javascript test harness to measure the time taken by each algorithm to sort the same dataset.