Lecture 1
Lecture 1
• Users instantiate and work with the ADT; can see only the external
operations / behavior
ADT Example
Example: Stack
• Contains various values of like type
• May have maximum size
• Values of appropriate type can be added to or removed from the stack
• Push operation adds a value to the stack
• Pop operation removes the last added value from the stack (LIFO)
• Is_Empty operation tells whether stack contains any values
• Is_Full operation tells whether stack is full (if applicable)
• It is an error to Pop from an empty stack
ADT implementation int Pop (stack* s)
{
typedef struct
if ( s -> cur_pos == 0 )
{
{printf("Stack empty!\n“);
int cur_pos ;
return -1; }
int array [ 100 ] ; // at most 100 elements in stack
else
} stack;
return s -> array [ -- s -> cur_pos ];
void Init ( stack* s )
}
{
void main()
s -> cur_pos = 0;
{
}
stack s1, s2; int x,y;
void Push ( stack* s, int x )
Init ( &s1 ); Init( &s2 );
{
Push ( &s1, 7 );
if ( s -> cur_pos == 100 )
Push ( &s2, 9 ); // Good...
printf("Stack full!\n“);
x = Pop ( &s2 );
else
y = Pop ( &s1 );
s -> array [ s -> cur_pos ++ ] = x;
x = s1.array[187];
}
s2.array[503] = 6; // ... and bad
s2.cur_pos = -
3;
}
Algorithms
• A process or a set of well-defined instructions to solve a particular
problem
• It takes a set of input and produces a desired output
Example
An algorithm to add two numbers:
• Take two number inputs
• Add numbers using the + operator
• Display the result
Properties of Algorithm
• Input and output should be defined precisely.
• Each step in the algorithm should be clear and unambiguous.
• Algorithms should be most effective among many different ways to
solve a problem.
• An algorithm shouldn't include computer code. Instead, the algorithm
should be written in such a way that it can be used in different
programming languages.
Pseudocode
• Pseudocode gives a high-level description of an algorithm without the
ambiguity associated with plain text but also without the need to
know the syntax of a particular programming language
Step 5: Stop
Flow Chart
• A flowchart is a type of
diagram that represents an
algorithm, workflow or
process.
• It shows the steps as boxes
of various kinds, and their
order by connecting the
boxes with arrows.
• Diagrammatic
representation illustrates a
solution model to a given
problem
Flow Chart: Maximum of two numbers
Example-Algorithm
Algorithm: Insertion-Sort
• Input: A list L of integers of length n
• Output: A sorted list L1 containing those integers present in L
• Step 1: Keep a sorted list L1 which starts off empty
• Step 2: Perform Step 3 for each element in the original list L
• Step 3: Insert it into the correct position in the sorted list L1.
• Step 4: Return the sorted list
• Step 5: Stop
Example-Pseudocode
for i <- 1 to length(A)
x <- A[i]
j <- i
while j > 0 and A[j-1] > x
A[j] <- A[j-1]
j <- j - 1
A[j] <- x