Sei sulla pagina 1di 38

Data Structures and Algorithms

unit - 1

Topics: Definition- Classification of data


structures: primitive and non-primitive-
Operations on data structures- Algorithm
Analysis- Simple Generic Classes and Interfaces
Definition
● Data structures is the way of storing and organizing
large amounts of data in a computer and representing
the relationships among data so that it can be used
efficiently.

● Example: Arrays, files, linked lists, stacks, queues,


trees, graphs, …etc.
Classification of data structures
Algorithm Analysis

What is an Algorithm?
● Step-wise procedure or instruction to solve a given
problem.
Why algorithm analysis?
● Helps to determine an efficient algorithm in terms of
time and space consumed.
Goal – to compare the algorithms – in terms of running
time, memory consumed, developers effort, etc…
How to Compare Algorithms?
1. Time Complexity– running time or processing time
 How fast an algorithm is?
 What affects its running time?
2. Space complexity – amount of computer memory
required during program execution.
 Data structures takes space
 What kind of data structure
 How does the choice of data structure affects the
space?
Types of Analysis
Mathematical Notations for time complexity
Asymptotic notation
1. Big-O notation - Running time functions of
algorithms are assessed more precisely using Big-Oh
2. Omega notation
3. Theta notation
Big-O notation
● Order notation - Defines that g(n) is the tight upper bound for
a given function f(n). f(n) and g(n) are two different functions to
be compared with.
f(n) = O( g(n) )

if there is a real constant c > 0 and an integer constant n0 >= 1


such that,
f(n) <= c g(n) for n >= n0

less than or equal up


to a constant factor for large values of n

This can also be written as, 0<= f(n) <=c g(n) for n >= n0
Big-O notation
Example:
Given algorithm: f(n) = n4+100n2+10n+50
g(n)= n4
Hence f(n)=O(n4)
Proof:
1. f(n)<=c g(n)  n4+100n2+10n+50 <= n4
2. If we assign c=2,
then n4+100n2+10n+50 <= 2n4
Big-O notation
Example:
Given algorithm: f(n) = 2n+5
g(n)= n
Hence f(n)=O(n)
Proof:
1. f(n)<=c g(n)  2n + 5 <= n
2. If we assign c=3, then 2n + 5 <= 3n
Big-O notation

c g(n) = 3n
f(n) = 2n+5

g(n) = n

point where 3n
“beats” 2n+5

2n+5 is O( n )

11
Uses of Big-O notation
Big-Oh allows us to ignore constant factors and
lower order (or less dominant) terms

2n2 + 5n – 4 is O( n2 )

constants lower order terms


arrayMax Example: Big-O notation
Algorithm arrayMax(A,n):
Input: An array A storing n integers.
Output: The maximum element in A.
currentMax  A[0]
for i  1 to n do
if currentMax < A[i] then
currentMax  A[i]
return currentMax

f(n) = O(n)
Functions by increasing growth rate
● The constant function: f(n) = 1
● The logarithm function: f(n) = log n
● The linear function: f(n) = n
● The n log n function: f(n) = n log n
● The quadratic function: f(n) = n2
● The cubic function: f(n) = n3
● The exponential function: f(n) = 2n
Example - Functions by increasing growth
rate

log n n n log n n2 n3 2n
0 1 0 1 1 2
1 2 2 4 8 4
2 4 8 16 64 16
3 8 24 64 512 256
4 16 64 256 4096 65536
5 32 160 1024 32768 4294967296
Big-Omega notation
● Defines that g(n) is the tight lower bound for a given
function f(n). f(n) and g(n) are two different functions to be
compared with.
f(n) = (g(n) )

if there is a real constant c > 0 and an integer constant n0 >=


1 such that,
f(n) >= c g(n) for n >= n0

greater than or equal


to a constant factor for large values of n

This can also be written as, 0<= c g(n) <= f(n) for n >= n0
Big-Omega notation
Example:

Find the lower bound for f(n) = 5n2

Solution:
f(n)= (n2)

0<= c g(n) <= f(n) for n >= n0


c n2 <= 5n2
If c=1, then n2 <= 5n2
Big-Theta notation
● f(n) lies between upper and lower bounds of g(n).
f(n) and g(n) are two different functions to be
compared with.
f(n) = (g(n))

if and only if f(n) = O(g(n)) and f(n) = (g(n)).

c1(g(n)) <= f(n) <= c2(g(n))


Big-Theta notation
Example:
Find  bound for f(n)=n2/2-n/2

Solution:
f(n)= (n2)

c1(g(n)) <= f(n) <= c2(g(n))

n2/5 <= n2/2-n/2 <= n2


c1=1/5 and c2=1
Space Complexity
Total space taken by the algorithm w.r.t. input size.
1. Fixed space requirement
1. Independent on the input character
2. Eg: instruction space, variables, etc
2. Auxiliary space (extra space)
1. Dependent on the input character
2. Eg: number, size, values, stack, formal and local
parameters, etc..
Guidelines for Asymptotic Analysis
1. Loops – The running time of a loop is almost the
running time of statements inside the loop.
2. Nested Loops – Total running time is the product of
sizes of all the loops.
3. Consecutive Statements – each consecutive
statements gets a running time of 1.
4. If-then-else statements – running time is calculated
for either if or else part
5. Logarithmic complexity – for multiplication and
division, the running time reduces to half
Guidelines for Asymptotic Analysis
Loops

for(i=1;i<=n;i++)
m=m+2;

O(n)
Guidelines for Asymptotic Analysis
Nested Loops

for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
m=m+2;

O(n2)
Guidelines for Asymptotic Analysis
Consecutive statements

x=x+1;
for(i=1;i<=n;i++){
m=m+2;
}
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
k=k+2;}}

Total time = c0+c1.n+c2. n2 = O(n2)


Guidelines for Asymptotic Analysis
If-then-else statements

if (length()==0){
return false;}
else{
for(n=0;n<length();n++){
if(a==b){
return false;
}}

Total time = c0+c1+(c2 +c3)n = O(n)


Guidelines for Asymptotic Analysis
logarithmic statements

for(i=1;i<=n;i++)
{
i=i*2;
}

Total time = O(logn)


Simple Generic Classes and Interfaces
● Generics in Java is similar to templates in C++.
● It allows common data types (instead of specific data
types - Integer, String, … etc and user defined types) as
parameter to methods, classes and interfaces.
● Java Collection classes use generics very well - HashSet
Class, TreeSet Class, ArrayList Class, LinkedList Class, HashMap Class,
TreeMap Class, PriorityQueue Class
Generic Classes
● Generics was first introduced in Java5.
● Now it is one of the most profound feature of java programming language.
● Generic programming enables the programmer to create classes, interfaces
and methods in which data type is specified as a parameter.
● It provides a facility to write an algorithm independent of any specific data
type.
● Generics also provide type safety - ensuring that an operation is being
performed on the right data type before executing that operation.
● Using Generics, it has become possible to create a single class, interface or
method that automatically works with all types of data (Integer, String,
Float etc).
● It has expanded the ability to reuse the code safely and easily.
● Before Generics was introduced, generalized classes, interfaces or methods
were created using references of type Object because Object is the super
class of all classes in Java, but this way of programming did not ensure type
safety.
Simple Generic Classes and Interfaces
● Generic classes
● Generic Methods
● Generic Interfaces
Generic Classes
Syntax:
public class Classname<Type parameter> {
}

Object creation:
Classname <data type> objectname = new Classname<data type> ();
OR
Classname <data type> objectname = new Classname<>();
Example Program - Generic Classes
Generic Classes
● In the above program, we first passed an Integer type
parameter to the Generic class.
● Then, we passed a String type parameter to the same
Generic class.
● Hence, we reused the same class for two different data
types.
● Thus, Generics helps in code reusability with ease.

Generic Classes – with more than one parameter
class Gen <T1,T2> {
T1 name;
T2 value;
Gen(T1 o1,T2 o2) {
name = o1;
value = o2;
}
public T1 getName() {
return name;
}
public T2 getValue() {
return value;
}}
class Test {
public static void main (String[] args) {
Gen < String,Integer> obj = new Gen< String,Integer >("StudyTonight",1);
String s = obj.getName();
System.out.println(s);
Integer i = obj.getValue();
System.out.println(i);
}}
Points to be considered
● Generics Work Only with Objects
Gen<int> iob = new Gen<int>(07); //Error, can't use
primitive type
● Generics Types of different Type Arguments are
never same
iob = sob; //Absolutely Wrong
● An array of Generic type cannot be created

T a[]; //this is allowed

T a[] = new T[10]; //this is not allowed


Generic Methods
You can also create generic methods that can be called with different
types of arguments. Based on the type of arguments passed to generic
method, the compiler handles each method.

Syntax:
<type-parameter> returntype methodname (parameters) {...}

Example:
Static <T> void display (T t)
{

}
Generic Methods – Example
package javaapplication13;
public class GenMethod {
static <T> void display (T[] t)
{
for(T arr:t)
{
System.out.printf("%s\t", arr);
}
System.out.println();
}
public static void main(String[] args)
{
Integer[] iob={1,2,3,4,5};
Double[] dob={1.1,2.1,3.1,4.1,5.1};
Character[] cob={'a','b','c','d','e'};
System.out.println("integer");
display(iob);
System.out.println("double");
display(dob);
System.out.println("character");
display(cob);
}}
Generic Interfaces
Like classes and methods, you can also create generic interfaces.

Syntax:

interface interface-name<type-param-list> { // ...}

Inside class:

class classname<type-param-list> implements interfacename<type-arg-list>


{
}
Generic Interfaces
interface MinMax<T extends Comparable<T>> {
T max();
}
class MyClass<T extends Comparable<T>> implements MinMax<T> {
T[] vals;
MyClass(T[] o) {
vals = o;
}
public T max() {
T v = vals[0];
for (int i = 1; i < vals.length; i++) {
if (vals[i].compareTo(v) > 0) {
v = vals[i];
} }
return v;
}}
public class Geninter {
public static void main(String args[]) {
Integer inums[] = { 3, 6, 2, 8, 6 };
Character chs[] = { 'b', 'r', 'p', 'w' };
MyClass<Integer> a = new MyClass<Integer>(inums);
MyClass<Character> b = new MyClass<Character>(chs);
System.out.println(a.max());
System.out.println(b.max());
}}

Potrebbero piacerti anche