100 likes | 103 Views
Analysis of ArrayList. Adding an element. We denote by n the size of the array when calling the method. Worst case space complexity?. if(not enough space){ create a bigger new array copy the elements } add element at index index++. We create an array of size 2n. 2n is in O(n).
E N D
Adding an element We denote by n the size of the array when calling the method. Worst case space complexity? if(not enough space){ create a bigger new array copy the elements } add element at index index++ We create an array of size 2n 2n is in O(n) Analysis of ArrayList
Adding an element We denote by n the size of the array when calling the method. Worst case time complexity? if(not enough space){ create a bigger new array copy the elements } add element at index index++ We copy all the elements. O(n) Analysis of ArrayList
Accessing an element We denote by n the size of the array when calling the method. Worst case space complexity? It does not consume space so 0. return T[i]; Remember: all constants belong to the class of complexity O(1), so this is still O(1) Analysis of ArrayList
Accessing an element We denote by n the size of the array when calling the method. Worst case time complexity? We get it right away, no intermediate operations needed. return T[i]; O(1) Analysis of ArrayList
Deleting an element We denote by n the size of the array when calling the method. Worst case space complexity? for(int i = target; i<size-1;i++) T[i] = T[i+1] T[size-1]=null; We don’t declare extra variables. O(1) Analysis of ArrayList
Deleting an element We denote by n the size of the array when calling the method. Worst case time complexity? for(int i = target; i<size-1;i++) T[i] = T[i+1] T[size-1]=null; If we delete the first one, we shift all the elements. O(n) Analysis of ArrayList
Searching an element We denote by n the size of the array when calling the method. Worst case space complexity? for(int i = 0; i<size; i++) if(T[i] == e) return true; return false; We don’t declare extra variables. O(1) Analysis of ArrayList
Searching an element We denote by n the size of the array when calling the method. Worst case time complexity? for(int i = 0; i<size; i++) if(T[i] == e) return true; return false; We’ll look through all elements. We saw an optimized methods that delete the comparison, but that’s improving by a factor 2, which does not show up with O notation. O(n) Analysis of ArrayList
Summary Analysis of ArrayList