DSA Lecture 2 - 3
DSA Lecture 2 - 3
Algorithms
Lecture 2 & 3
Outline
• UML Diagrams
• Concepts of Object Oriented Design
UML
Diagrams
Concepts of Object
Oriented Design
13
Array variations
• The array indices may be integers (C, Java) or other
discrete data types (Pascal, Ada)
14
Arrays in Java I
• Array indices are integers
• An array of length n has bounds 0 and n-1
• Arrays are homogeneous
• However, an array of an object type may contain objects
of any subtype of that object
• For example, an array of Animal may contain objects of type
Cat and objects of type Dog
• An array of Object may contain any type of object (but cannot
contain primitives)
15
Arrays in Java II
• Arrays are objects
• Arrays are allocated by new, manipulated by reference, and garbage
collected
• However, the usual bracket notation a[i] is provided as syntactic sugar
• Arrays are reflective
• a.length is the length of array a
• a.getClass() is the type of array a
• An array of integers has type [I
• An array of Strings has type [Ljava.lang.String;
16
Arrays in Java III
• Here’s one way to visualize an array in Java:
myArray
class tag [I
length
4
0 17
1 23
2 948
3 3
17
Subarrays
• A subarray is a consecutive portion of an array
0 1 2 3 4 5 6 7 8 9
array a [I 10 1 1 2 3 5 8 13 21 34 55
subarray a[2...6]
19
ADT (abstract
datatype)
• The abstract datatype is special
kind of datatype, whose
behavior is defined by a set of
values and set of operations.
The keyword “Abstract” is used
as we can use these datatypes,
we can perform different
operations. But how those
operations are working that is
totally hidden from the user.
Two-dimensional arrays I
• Some languages (Fortran, Pascal) support two-dimensional (2D)
arrays: columns
23
Operations in arrays
{
a= source array
If (n<a.length) throw new aa= target array
IllegalArgumentException(); m= starting index of source array
Int[] aa=new int[n]; mm= starting index of target array
System.arraycopy(a,0,aa,0, a.length); k= number of elements copied
return aa;
}
Inserting an element into an array
• Suppose we want to insert the value 8 into this sorted array
(while keeping the array sorted)
1 3 3 7 12 14 17 19 22 30
• We can do this by shifting all the elements after the mark right by
one location
• Of course, we have to discard the 30 when we do this
1 3 3 7 8 12 14 17 19 22 30
1 3 3 7 8 12 14 17 19 22
1 3 3 7 12 14 17 19 22 ?
28
Arrays
• Here are the advantages of arrays:
• Very efficient, in terms of both time and space
• Convenient syntax
• Here is the main disadvantage:
• Fixed size
29
Conclusions
• Arrays are not identical in all languages
30