CPSC 331 Final Revision 2
CPSC 331 Final Revision 2
1
44 if ( element . compareTo ( current . data ) == 0) {
45 return true ;
46 }
47
48 return element . compareTo ( current . data ) < 0 ?
c o n t a i n s R e c u r s i v e ( current . left , element ) :
c o n t a i n s R e c u r s i v e ( current . right , element ) ;
49 }
50
51 // O ( n ) - Worst case && O ( log n ) - Average case
52 public void remove ( T element ) {
53 root = re mo v eR ec ur s iv e ( root , element ) ;
54 }
55
56 private Node r em ov eR e cu rs iv e ( Node current , T element ) {
57 if ( current == null ) {
58 return null ;
59 }
60
61 if ( element . compareTo ( current . data ) == 0) {
62 if ( current . left == null && current . right == null ) {
63 return null ;
64 }
65 if ( current . right == null ) {
66 return current . left ;
67 }
68 if ( current . left == null ) {
69 return current . right ;
70 }
71 T smallestValue = f i n d S m a l l e s t V a l u e ( current . right ) ;
72 current . data = smallestValue ;
73 current . right = re mo v eR ec ur s iv e ( current . right ,
smallestValue ) ;
74 return current ;
75 }
76
77 if ( element . compareTo ( current . data ) < 0) {
78 current . left = r e mo ve Re c ur si v e ( current . left , element ) ;
79 } else {
80 current . right = re mo v eR ec ur s iv e ( current . right , element )
;
81 }
82 return current ;
83 }
84
85 // O ( n )
86 public int getHeight () {
87 return h ei g ht Re cu r si ve ( root ) ;
88 }
89
90 private int he ig h tR ec u rs iv e ( Node node ) {
91 if ( node == null ) return 0;
92 return 1 + Math . max ( he ig h tR ec ur s iv e ( node . left ) ,
h ei gh tR e cu rs iv e ( node . right ) ) ;
93 }
94
95 // O (1)
2
96 public T getNext ( int order ) {
97 if ( current >= 0 && current < traversalList . size () ) {
98 return traversalList . get ( current ++) ;
99 }
100 return null ;
101 }
102
103 // O ( n )
104 public T findMax () {
105 if ( isEmpty () ) {
106 return null ;
107 }
108 Node current = root ;
109 while ( current . right != null ) {
110 current = current . right ;
111 }
112 return current . data ;
113 }
114
115 // O ( n )
116 public T findMin () {
117 if ( isEmpty () ) {
118 return null ;
119 }
120 Node current = root ;
121 while ( current . left != null ) {
122 current = current . left ;
123 }
124 return current . data ;
125 }
126 }
implementations/BST.java
Red-Black-Tree Implementation
1 public class RBT < T extends Comparable <T > >{
2 private class Node {
3 private T value ;
4 private Node left , right , parent ;
5 private boolean color ; // true = black , false = red
6 }
7
8 public Node root ;
9 public final boolean BLACK = true ;
10 public final boolean RED = false ;
11 public final Node NIL ; // S e n t i n e l node
12
13 public RBT () {
14 NIL = new Node () ;
15 NIL . color = BLACK ; // NIL nodes are always black
16 root = NIL ; // Initially , the root is NIL
17 }
18
19 public Node search ( T value ) {
3
20 Node current = root ;
21 while ( current != NIL && value . compareTo ( current . value ) !=
0) {
22 if ( value . compareTo ( current . value ) < 0) {
23 current = current . left ;
24 } else {
25 current = current . right ;
26 }
27 }
28 return current ;
29 }
30
31 public Node minimum ( Node node ) {
32 while ( node . left != NIL ) {
33 node = node . left ;
34 }
35 return node ;
36 }
37
38 public String delete ( T k ) {
39 Node z = search ( k ) ;
40
41 if ( z == NIL ) {
42 return " Key not found ! " ;
43 }
44
45 Node x , y = z ;
46 boolean yOr iginalC olor = y . color ;
47
48 if ( z . left == NIL ) {
49 x = z . right ;
50 transplant (z , z . right ) ;
51 } else if ( z . right == NIL ) {
52 x = z . left ;
53 transplant (z , z . left ) ;
54 } else {
55 y = minimum ( z . right ) ;
56 yOri ginalCol or = y . color ;
57 x = y . right ;
58
59 if ( y . parent == z ) {
60 x . parent = y ;
61 } else {
62 transplant (y , y . right ) ;
63 y . right = z . right ;
64 y . right . parent = y ;
65 }
66
67 transplant (z , y ) ;
68 y . left = z . left ;
69 y . left . parent = y ;
70 y . color = z . color ;
71 }
72
73 if ( yOrigina lColor == BLACK ) {
74 deleteFixup ( x ) ;
75 }
4
76 return " Node deleted " ;
77 }
78
79 private void deleteFixup ( Node x ) {
80 while ( x != root && x . color == BLACK ) {
81 if ( x == x . parent . left ) {
82 Node w = x . parent . right ;
83 if ( w . color == RED ) {
84 w . color = BLACK ;
85 x . parent . color = RED ;
86 leftRotate ( x . parent ) ;
87 w = x . parent . right ;
88 }
89 if ( w . left . color == BLACK && w . right . color == BLACK
) {
90 w . color = RED ;
91 x = x . parent ;
92 } else {
93 if ( w . right . color == BLACK ) {
94 w . left . color = BLACK ;
95 w . color = RED ;
96 rightRotate ( w ) ;
97 w = x . parent . right ;
98 }
99 w . color = x . parent . color ;
100 x . parent . color = BLACK ;
101 w . right . color = BLACK ;
102 leftRotate ( x . parent ) ;
103 x = root ;
104 }
105 } else {
106 Node w = x . parent . left ;
107 if ( w . color == RED ) {
108 w . color = BLACK ;
109 x . parent . color = RED ;
110 rightRotate ( x . parent ) ;
111 w = x . parent . left ;
112 }
113 if ( w . right . color == BLACK && w . left . color == BLACK
) {
114 w . color = RED ;
115 x = x . parent ;
116 } else {
117 if ( w . left . color == BLACK ) {
118 w . right . color = BLACK ;
119 w . color = RED ;
120 leftRotate ( w ) ;
121 w = x . parent . left ;
122 }
123 w . color = x . parent . color ;
124 x . parent . color = BLACK ;
125 w . left . color = BLACK ;
126 rightRotate ( x . parent ) ;
127 x = root ;
128 }
129 }
130 }
5
131 x . color = BLACK ;
132 }
133
134 private void transplant ( Node u , Node v ) {
135 if ( u . parent == null ) {
136 root = v ;
137 } else if ( u == u . parent . left ) {
138 u . parent . left = v ;
139 } else {
140 u . parent . right = v ;
141 }
142 v . parent = u . parent ;
143 }
144
145 public void add ( T item ) {
146 Node tmp = root ;
147 Node parent = null ;
148
149 while ( tmp != null ) {
150 parent = tmp ;
151 if ( item . compareTo ( tmp . value ) == 0) {
152 return ;
153 }
154 else if ( item . compareTo ( tmp . value ) < 0) {
155 tmp = tmp . left ;
156 } else {
157 tmp = tmp . right ;
158 }
159 }
160
161 Node nn = new Node () ;
162 nn . value = item ;
163 nn . color = false ; // new node is red
164 if ( parent == null ) {
165 root = nn ;
166 nn . color = true ; // root is black
167 }
168 else if ( item . compareTo ( parent . value ) < 0) parent . left = nn
;
169 else parent . right = nn ;
170 nn . parent = parent ;
171 fixAfterAdd ( nn ) ;
172 root . color = true ; // root is black
173 }
174
175 private Node getPibling ( Node parent ) {
176 Node grandParent = parent . parent ;
177 if ( grandParent . left == parent ) return grandParent . right ;
178 else return grandParent . left ;
179 }
180
181 private void fixAfterAdd ( Node nn ) {
182 Node parent = nn . parent ;
183 if ( parent == null ) return ;
184 if ( parent . color == true ) return ;
185
186 Node grandParent = parent . parent ;
6
187 Node pibling = getPibling ( parent ) ;
188
189 if ( pibling != null && pibling . color == false ) {
190 parent . color = true ;
191 pibling . color = true ;
192 grandParent . color = false ;
193 fixAfterAdd ( grandParent ) ;
194 } else if ( parent == grandParent . left ) {
195 if ( nn == parent . right ) {
196 leftRotate ( parent ) ;
197 parent = nn ;
198 }
199 rightRotate ( grandParent ) ;
200 parent . color = true ;
201 grandParent . color = false ;
202 } else {
203 if ( nn == parent . left ) {
204 rightRotate ( parent ) ;
205 parent = nn ;
206 }
207 leftRotate ( grandParent ) ;
208 parent . color = true ;
209 grandParent . color = false ;
210 }
211 }
212
213 private void f i x P a r e n t C h i l d R e l a t i o n ( Node parent , Node n , Node
child ) {
214 if ( parent == null ) {
215 root = child ;
216 } else if ( parent . left == n ) {
217 parent . left = child ;
218 } else if ( parent . right == n ) {
219 parent . right = child ;
220 }
221
222 if ( child != null ) {
223 child . parent = parent ;
224 }
225 }
226
227 private void rightRotate ( Node n ) {
228 Node parent = n . parent ;
229 Node leftChild = n . left ;
230 n . left = leftChild . right ;
231 if ( leftChild . right != null ) {
232 leftChild . right . parent = n ;
233 }
234 leftChild . right = n ;
235 n . parent = leftChild ;
236 f i x P a r e n t C h i l d R e l a t i o n ( parent , n , leftChild ) ;
237 }
238
239 private void leftRotate ( Node n ) throws Exception {
240 try {
241 Node parent = n . parent ;
242 Node rightChild = n . right ;
7
243 n . right = rightChild . left ;
244 if ( rightChild . left != null ) {
245 rightChild . left . parent = n ;
246 }
247 rightChild . left = n ;
248 n . parent = rightChild ;
249 f i x P a r e n t C h i l d R e l a t i o n ( parent , n , rightChild ) ;
250 } catch ( Exception e ) {
251 e . pr i nt St ac k Tr ac e () ;
252 }
253 }
254 }
implementations/RBT.java
8
Deletion in Red-Black Tree rules
9
9 }
10
11 // O ( log n )
12 public void enqueue ( T item ) {
13 queue [ size ] = item ;
14
15 int loc = size ;
16 int parent = ( loc - 1) / 2;
17 while ( loc > 0 && (( Comparable ) queue [ loc ]) . compareTo ( queue
[ parent ]) > 0) {
18 swap ( loc , parent ) ;
19 loc = parent ;
20 parent = ( loc - 1) / 2;
21 }
22 size ++;
23 }
24
25 // O ( log n )
26 public T dequeue () {
27 T max = queue [0];
28 queue [0] = queue [ size - 1];
29 sink (0) ;
30 queue [ size - 1] = null ;
31 size - -;
32 return max ;
33 }
34
35 private void sink ( int loc ) {
36 int left = 2 * loc + 1;
37 int right = 2 * loc + 2;
38 int largest = loc ;
39 T tmp = queue [ loc ];
40
41 if ( left > ( size - 1) ) return ;
42 else if ( left == size - 1) {
43 if ((( Comparable ) tmp ) . compareTo ( queue [ left ]) < 0) swap (
loc , left ) ;
44 } else {
45 if ((( Comparable ) queue [ left ]) . compareTo ( queue [ right ]) <
0) largest = right ;
46 else largest = left ;
47 if ((( Comparable ) tmp ) . compareTo ( queue [ largest ]) < 0) {
48 swap ( loc , largest ) ;
49 sink ( largest ) ;
50 }
51 }
52 }
53 }
implementations/MaxHeap.java
10
7 queue [ i ] = queue [ j ];
8 queue [ j ] = temp ;
9 }
10
11 // O ( log n )
12 public void enqueue ( T item ) {
13 queue [ size ] = item ;
14
15 int loc = size ;
16 int parent = ( loc - 1) / 2;
17 while ( loc > 0 && queue [ loc ]. compareTo ( queue [ parent ]) < 0)
{
18 swap ( loc , parent ) ;
19 loc = parent ;
20 parent = ( loc - 1) / 2;
21 }
22 size ++;
23 }
24
25 // O ( log n )
26 public T dequeue () {
27 T min = queue [0];
28 queue [0] = queue [ size - 1];
29 sink (0) ;
30 queue [ size - 1] = null ;
31 size - -;
32 return min ;
33 }
34
35 private void sink ( int loc ) {
36 int left = 2 * loc + 1;
37 int right = 2 * loc + 2;
38 int smallest = loc ;
39 T tmp = queue [ loc ];
40
41 if ( left > ( size - 1) ) return ;
42 else if ( left == size - 1) {
43 if ( tmp . compareTo ( queue [ left ]) > 0) swap ( loc , left ) ;
44 } else {
45 if ( queue [ left ]. compareTo ( queue [ right ]) > 0) smallest =
right ;
46 else smallest = left ;
47 if ( tmp . compareTo ( queue [ smallest ]) > 0) {
48 swap ( loc , smallest ) ;
49 sink ( smallest ) ;
50 }
51 }
52 }
53 }
implementations/MinHeap.java
11
1 public class L i n e a r P r o b i n g H a s h T a b l e {
2 private Integer [] table ;
3 private int capacity ;
4 private Integer DELETED = Integer . MIN_VALUE ;
5
6 // O (1)
7 private int hash ( int key , int i ) {
8 return ( key % capacity + i ) % capacity ;
9 }
10
11 // O ( n ) - worst case && O (1) - best case
12 public int insert ( int key ) {
13 for ( int i = 0; i < capacity ; i ++) {
14 int j = hash ( key , i ) ;
15 if ( table [ j ] == null || table [ j ] == DELETED ) {
16 table [ j ] = key ;
17 return j ;
18 }
19 }
20 throw new T a b l e F u l l E x c e p t i o n ( " Table is full " ) ;
21 }
22
23 // O ( n ) - worst case && O (1) - best case
24 public int search ( int key ) {
25 for ( int i = 0; i < capacity ; i ++) {
26 int j = hash ( key , i ) ;
27 if ( table [ j ] == key ) {
28 return j ;
29 } else if ( table [ j ] == null ) {
30 throw new N o S u c h E l e m e n t E x c e p t i o n ( " Element not found
");
31 }
32 }
33 }
34
35 // O ( n ) - worst case && O (1) - best case
36 public void delete ( int key ) {
37 for ( int i = 0; i < capacity ; i ++) {
38 int j = hash ( key , i ) ;
39 if ( table [ j ] == key ) {
40 table [ j ] = DELETED ;
41 return ;
42 } else if ( table [ j ] == null ) {
43 throw new N o S u c h E l e m e n t E x c e p t i o n ( " Element not found
");
44 }
45 }
46 throw new N o S u c h E l e m e n t E x c e p t i o n ( " Element not found after
full table scan " ) ;
47 }
48 }
implementations/LinearProbingHashTable.java
12
Sorting Algorithms’ Implementations
1 public class Sort {
2 // O (1)
3 private void swap ( int i , int j , BoundedList list ) {
4 T tmp = list [ i ];
5 list [ i ] = list [ j - 1];
6 list [ j - 1] = tmp ;
7 }
8
9 // O ( n ) - Worst case && O ( n ) - Best case && Average case
10 public void BubbleSort ( BoundedList list ) {
11 for ( int i = 0; i < list . size () ; i ++) {
12 for ( int j = list . size () - 1; j > i ; j - -) {
13 if ( list [ j ]. compareTo ( list [ j - 1]) < 0) {
14 swap (j , j , list ) ;
15 }
16 }
17 }
18 }
19
20 // O ( n ) - Worst case && O ( n ) - Best case && Average case
21 public void InsertionSort ( BoundedList list ) {
22 for ( int i = 1; i < list . size () ; i ++) {
23 for ( int j = i ; j > 0; j - -) {
24 if ( list [ j ]. compareTo ( list [ j - 1]) < 0) {
25 swap (j , j , list ) ;
26 }
27 }
28 }
29 }
30
31 // O ( n )
32 private T getMinIndex ( BoundedList list ) {
33 T min_so_far = list [0];
34 for ( int i = 1; i < list . size () ; i ++) {
35 if ( list [ i ] < min_so_far ) {
36 min_so_far = list [ i ];
37 }
38 }
39 return min_so_far ;
40 }
41
42 // O ( n ) - Best case && Worst case && Average case
43 public void SelectionSort ( BoundedList list ) {
44 for ( int i = 0; i < list . size () ; i ++) {
45 int minIndex = getMinIndex ( list ) ;
46 swap (i , minIndex , list ) ;
47 }
48 }
49
50 // O ( n log n ) - Best case && Worst case && Average case
51 public void HeapSort ( BoundedList list ) {
52 MinHeap heap = new MinHeap () ;
53
54 // O ( n ) for the loop and O ( log n ) for the enqueue
55 for ( int i = 0; i < list . size () ; i ++) {
13
56 heap . enqueue ( list [ i ]) ;
57 }
58
59 // O ( n ) for the loop and O ( log n ) for the dequeue
60 for ( int i = 0; i < list . size () ; i ++) {
61 list [ i ] = heap . dequeue () ;
62 }
63
64 // Giving us a total of O ( n log n )
65 }
66
67 // O ( n )
68 private void Merge ( BoundedList left , BoundedList right ,
BoundedList list ) {
69 int i = 0;
70 int j = 0;
71 int k = 0;
72
73 while ( i < left . size () && j < right . size () ) {
74 if ( left [ i ]. compareTo ( right [ j ]) < 0) {
75 list [ k ] = left [ i ];
76 i ++;
77 } else {
78 list [ k ] = right [ j ];
79 j ++;
80 }
81 k ++;
82 }
83
84 while ( i < left . size () ) {
85 list [ k ] = left [ i ];
86 i ++;
87 k ++;
88 }
89
90 while ( j < right . size () ) {
91 list [ k ] = right [ j ];
92 j ++;
93 k ++;
94 }
95 }
96
97 // O ( n log n ) - Best case && Worst case && Average case
98 public void MergeSort ( BoundedList list ) {
99 if ( list . size () <= 1) {
100 return ;
101 }
102
103 int mid = list . size () / 2;
104 BoundedList left = new BoundedList ( mid ) ;
105 BoundedList right = new BoundedList ( list . size () - mid ) ;
106
107 for ( int i = 0; i < mid ; i ++) {
108 left [ i ] = list [ i ];
109 }
110
111 for ( int i = mid ; i < list . size () ; i ++) {
14
112 right [ i - mid ] = list [ i ];
113 }
114
115 MergeSort ( left ) ;
116 MergeSort ( right ) ;
117 Merge ( left , right , list ) ;
118 }
119
120 // O ( n )
121 private int Partition ( BoundedList list , int low , int high ) {
122 T pivot = list [ high ];
123 int i = low - 1;
124
125 for ( int j = low ; j < high ; j ++) {
126 if ( list [ j ] < pivot ) {
127 i ++;
128 swap (i , j , list ) ;
129 }
130 }
131
132 swap ( i + 1 , high , list ) ;
133 return i + 1;
134 }
135
136 // O ( n ) - Worst case && O ( n log n ) - Best case && Average
case
137 public void QuickSort ( BoundedList list , int low , int high ) {
138 if ( low < high ) {
139 int p = Partition ( list , low , high ) ;
140
141 QuickSort ( list , low , p - 1) ;
142 QuickSort ( list , p + 1 , high ) ;
143 }
144 }
145 }
implementations/Sort.java
15
16 while ( i < size ) {
17 if ( item . compareTo ( list [ i ]) == 0) return i ;
18 else if ( item . compareTo ( list [ i ]) > 0) return -1;
19 else i ++;
20 }
21 return -1;
22 }
23
24 // R e c u r s i v e Binary search - Sorted list - O ( log n )
25 public int contains ( T item ) {
26 return binarySearch ( item , 0 , size -1) ;
27 }
28
29 private int binarySearch ( T item , int low , int high ) {
30 if ( low > high ) return -1;
31 int mid = ( low + high ) / 2;
32 if ( item . compareTo ( list [ mid ]) == 0) return mid ;
33 else if ( item . compareTo ( list [ mid ]) < 0) return binarySearch (
item , low , mid -1) ;
34 else return binarySearch ( item , mid +1 , high ) ;
35 }
36
37 // I t e r a t i v e Binary search - Sorted list - O ( log n )
38 public int contains ( T item ) {
39 int low = 0;
40 int high = size -1;
41 while ( low <= high ) {
42 int mid = ( low + high ) / 2;
43 if ( item . compareTo ( list [ mid ]) == 0) return mid ;
44 else if ( item . compareTo ( list [ mid ]) < 0) high = mid -1;
45 else low = mid +1;
46 }
47 return -1;
48 }
49 }
implementations/Search.java
16
16
17 // 2 ways to do this part either this way or the way
below
18 ListIterator < Node > iter = adjList [ v ]. listIterator (0) ;
19 while ( iter . hasNext () ) {
20 Node n = iter . next () ;
21 int i = n . vertex . id ;
22 if (! visited [ i ]) s . push ( i ) ;
23 }
24
25 // OR
26
27 for ( int i = 0; i < size ; i ++) {
28 if (! visited [ i ] && adjMatrix [ v ][ i ] != null ) s . push ( i
);
29 }
30 }
31 return w ;
32 }
33
34 public LinkedQueue allSourceDFS ( Graph G , Vertex V , Edge E ) {
35 LinkedQueue < Integer > w = new LinkedQueue () ;
36 for ( Vertex v : V . vertices ) {
37 w [ v ] = oneSourceDFS ( v ) ;
38 }
39 return w ;
40 }
41
42 // Time c o m p l e x i t y : O ( V + E )
43 public LinkedQueue oneSourceBFS ( int startVertex ) {
44 Queue < Integer > q = new LinkedList () ;
45 LinkedQueue < Integer > w = new LinkedQueue () ;
46 boolean [] visited = new boolean [ size ];
47 for ( int i = 0; i < size ; i ++) visited [ i ] = false ;
48 q . enqueue ( startVertex ) ;
49 visited [ startVertex ] = true ;
50
51 while (! q . isEmpty () ) {
52 int v = q . dequeue () ;
53 w . enqueue ( v ) ;
54
55 // 2 ways to do this part either this way or the way
below
56 ListIterator < Node > iter = adjList [ v ]. listIterator (0) ;
57 while ( iter . hasNext () ) {
58 Node n = iter . next () ;
59 int i = n . vertex . id ;
60 if (! visited [ i ]) {
61 q . enqueue ( i ) ;
62 visited [ i ] = true ;
63 }
64 }
65
66 // OR
67
68 visited [ v ] = true ;
69 for ( int i = 0; i < size ; i ++) {
17
70 if (! visited [ i ] && adjMatrix [ v ][ i ] != null ) {
71 q . enqueue ( i ) ;
72 visited [ i ] = true ;
73 }
74 }
75 }
76 return w ;
77 }
78
79 public LinkedQueue allSourceBFS ( Graph G , Vertex V , Edge E ) {
80 LinkedQueue < Integer > w = new LinkedQueue () ;
81 for ( Vertex v : V . vertices ) {
82 w [ v ] = oneSourceBFS ( v ) ;
83 }
84 return w ;
85 }
86 }
implementations/BDFS.java
Dijkstra Algorithm
Pseudo-Code
1 import java . util . Set ;
2
3 public class Dijkstra {
4 public void ge tS h or te s tP at h ( int src ) {
5 PriorityQueue < Node > minHeap = new PriorityQueue < >(V ,
Comparator . comparingInt ( node -> node . weight ) ) ;
6 Set < Integer > set = new HashSet < >() ;
7 Arrays . fill ( distances , Integer . MAX_VALUE ) ;
8 minHeap . add ( new Node ( src , 0) ) ;
9 distances [ src ] = 0;
10 avai lablePat hs . put ( src , new LinkedList < >( Arrays . asList ( -1) )
);
11
18
12 while (! minHeap . isEmpty () ) {
13 int u = minHeap . remove () . vertex ;
14 if (! set . add ( u ) ) continue ;
15 for ( Node v : list_adj . get ( u ) ) {
16 if (! set . contains ( v . vertex ) ) {
17 int edgeDistance = v . weight ;
18 int newDist = distances [ u ] + edgeDistance ;
19
20 if ( newDist < distances [ v . vertex ]) {
21 distances [ v . vertex ] = newDist ;
22 avai lablePat hs . put ( v . vertex , new LinkedList
< >( Arrays . asList ( u ) ) ) ;
23 minHeap . add ( new Node ( v . vertex , distances [ v .
vertex ]) ) ;
24 } else if ( newDist == distances [ v . vertex ]) {
25 avai lablePat hs . get ( v . vertex ) . add ( u ) ;
26 minHeap . add ( new Node ( v . vertex , distances [ v .
vertex ]) ) ;
27 }
28 }
29 }
30 }
31 }
32 }
implementations/Dijkstra.java
19
Complexity for sorting algos
20
Possible Final Questions
Fill in the blanks for complexities of LLs
21
Proving the Height of a Complete Tree is
O(log n) by Induction
Base Case
For n = 1, the height h = 0, since there is only the root. Since log(1) = 0, the
base case holds.
Inductive Hypothesis
Assume that for a complete tree with k nodes, the height h is O(log k).
Inductive Step
We need to show that a tree with k + 1 nodes will have a height h that is
O(log(k + 1)). When you add an additional node to a complete tree with k
nodes, it will either fill up the last level or start a new level if the last level was
already full. Since a complete binary tree fills level by level, the height
increases by 1 when we move from a complete level to start a new level. The
number of nodes at that point is 2h+1 , where h is the height before adding the
new level. Thus, for a tree with k + 1 nodes, we have:
k + 1 2h+1
log(k + 1) log(2h+1 )
log(k + 1) h + 1
h log(k + 1) 1
This shows that the height of the tree is at least log(k + 1) 1, which is
O(log n).
22
Loop Invariant Proof for Dijkstra’s Algorithm
Loop Invariant for Dijkstra’s Algorithm: At the start of each iteration of the
repeat loop, the set S contains vertices for which we have found the minimum
cost path from the source s.
Proof of Correctness
Initialization: Initially, the set S contains only the source vertex s, and the
minimum cost path from s to itself is 0, which is trivially correct.
23
Shortest Path
Dijkstra’s Algorithm
Applications of DFS
Graph Traversal
Breadth-First (BFS)
• You visit every neighbor of the starting vertex, and then every neighbor of
each neighbor and so on until theres no more new vertices
• Can be visualized as every time you visit a vertex you add it to a queue and
when you visit all vertices connected to the vertex in front you dequeue and
keep doing this until the queue becomes empty
• ENQUEUE THE SMALLEST NEIGHBOR FOR EXAM PURPOSES
Complexity
Searching Algorithms
adds 1
Sorting Algorithms
Bubble Sort Algorithm
Complexity O(n2)
Correctness
Sorting Algorithms
Insertion Sort Algorithm
Complexity O(n2)
Correctness
Sorting Algorithms
Complexity O(n2)
Correctness
Sorting Algorithms
Heap Sort Algorithm
Complexity
O(n.logn)
Correctness
Sorting Algorithms
Algorithm to merge 2 sorted lists within an array A, A[low to mid] and A[mid+1 to high]
Seperating the 2
sorted lists into
separate arrays L
and R and then
inserting them
back into A
depending on
which is bigger.
And then adding
leftovers
Complexity of this
is O(n)
Correctness
Sorting Algorithms
Sorting Algorithms
Fastest on Average
Complexity is O(n)