chap 1
chap 1
Introduction to Algorithm
Data: Data is nothing but a fact or raw fact or part
of information that can be stored in computer.
Example: name of a person, name of a place, name
of things, any number of any type, a character,
string, photo, etc.
Variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within
that memory; and the set of operations that can be applied to the variable. The
name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C is case-sensitive.
Type variable_list;
Local Variables:
Variables that are declared inside a function or block are called local variables.
They can be used only by statements that are inside that function or block of
code. Local variables are not known to functions outside their own. Following is
the example using local variables. Here all the variables a, b and c are local to
main() function.
#include <stdio.h>
int main ()
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
return 0;
}
Global Variables
Global variables are defined outside of a function, usually on top of the program.
The global variables will hold their value throughout the lifetime of your program
and they can be accessed inside any of the functions defined for the program. A
global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. Following is
the example using global and local variables:
#include <stdio.h>
int g;
int main ()
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
return 0;
Data Types:
In the C programming language, data types refer to an extensive system used for
declaring variables or functions of different types. The type of a variable
determines how much space it occupies in storage and how the bit pattern stored
is interpreted.
Introduction to algorithm:
Insertion sort
Insertion sort works the way many people sort gin rummy hand.
We start with an empty left hand and the cards face down on the
table.
We then remove one card at a time from the table and insert it into
the correct position in the left hand.
To find the correct position for a card, we compare it with each of the
cards already in the hand, from right to left, as illustrated in Figure 1.1.
The input numbers are sorted in place: the numbers are rearranged
within the array A, with at most a constant number of them stored
outside the array at any time.
INSERTION−SORT (A)
Step 1 for i= 2 to length[A]
Step 2 do key= A[i]
Step 3 j= i − 1
Step 4 while j > 0 and A[j] > key
Step 5 do A[j + 1] =A[j]
Step 6 j =j − 1
Step 7 A[j + 1] =key
The index j indicates the "current card" being inserted into the hand.
At each iteration of the "outer" for loop, the element A[j] is picked out
of the array (line 2).
Despite there being some generalities each problem has its own
characteristics which demand specific responses to solve the problem
efficiently.
Within the framework of this last statement we will try to make a few
suggestions that can sometimes be useful in designing efficient
algorithms.
Redundant computations –
For ex:
X=0;
For(i=0;i<=n;i++)
{
x=x+0.01;
y=(a*a*a +c)*x*x + b*b*x;
Printf(“\n x= %f \t y= %f ”,x,y);
}
Just like:
P=a*a*a +c;
Q=b*b;
X=0;
For(i=0;i<=n;i++)
{
X=x+0.01;
Y= p*x*x + q*x;
Printf(“\n x= %f \t y= %f ”,x,y);
}
The savings in this instance are not all that significant but there are
many other situations where they are much more significant.
Version 1: Version 2:
P=1;
P=1; Max=a[1];
For(i=2;i<n+1;i++) For(i=2;i<n+1;i++)
{ {
If(a[i]>a[p]) If(a[i]>max)
P=I; {
Max=a[p]; MAX= A[I];
} P=I;
}
}
It sometimes happens, due to the nature of the input data, that the
algorithm establishes the desired output condition before the general
conditions for termination have been met.
For example, a bubble sort might be used to sort a set of data that is
already almost in sorted order.
When this happens it is very likely that the algorithm will have the
data in sorted order long before the loop termination conditions are
met.
If there have been no exchanges in the current pass the data must be
sorted and so early termination can be applied.
We are now left within the task of trying to measure the efficiency of
algorithm.
Analyzing algorithms:
Such analysis may indicate more than one viable candidate, but
several inferior algorithms are usually discarded in the process.
The running time of the algorithm is the sum of running times for each
statement executed; a statement that takes ci steps to execute and is
executed n times will contribute ci n to the total running time.
We must compare each element A[j] with each element in the entire
sorted subarray A[1. . j − 1], and so tj = j for j = 2,3, . . . , n. and we find
that in the worst case, the running time of INSERTION−SORT.
On average, half the elements in A[1. . j − 1] are less than A[j], and half
the elements are greater.
Often, we shall assume that all inputs of a given size are equally likely.
For instance:
There are other criteria for judging algorithms that have a more direct
relationship to performance.
Space/Time complexity
Space Complexity
This part typically includes the instruction space (i.e., space for the
code), space for simple variables and fixed-size component variables
(also called aggregate), space for constants, and soon.
Time Complexity
The time T(P) taken by a program P is the sum of the compile time and
the run (or execution) time.
Because many of the factors T(p) depends on are not known at the
time a program is conceived it, is reasonable to attempt only to
estimate T(p).
We can go one step further and count only the number of program
steps.
A program step is loosely defined as a syntactically or semantically
meaningful segment of a program that has an execution time that is
independent of the instance characteristics.
The control parts for ‘for’ and ‘while’ statements have the following
forms:
for % :=(expr)to (expr 1)do
while ((expr))do
The step count for each execution of the control part of a for
statement is one, unless the counts attributable to (expr) and (expr 1)
are functions of the instance characteristics.
In this latter case, the first execution of the control part of the ‘for’ has
a step count equal to the sum of the counts for (expr) and (expr 1)
(note that these expressions are computed only when the loop is
started).
Remaining executions of the ‘for’ statement have a step count of one
and soon.
Exchange
Problem: Given two variables, a and b, exchange the values assign to them.
Algorithm development
The problem of interchanging the values associated with two variables
involves a very fundamental mechanism that occurs in many sorting
and data manipulation algorithms.
To define the problem more clearly we will examine a specific
example. Consider that the variables a and b are assigned values as
outlined below.
That is,
Starting configuration
a = 721
b = 463
Target configuration
a = 463
b = 721
If we do,
a = b;
b= a;
a = b;
b= t;
Algorithm description
1. Save the original value of a in t.
2. Assign to a the original value of b.
3. Assign to b the original value of a that is stored in t.
Pascal implementation
Procedure exchange (var a,b :integer);
Var t : integer;
T := a;
A := b;
B := t;
End
Counting
Algorithm development
Generally a count must be made of the number of items in a set which
possess some particular property or which satisfy some particular
conditions.
As a starting point for developing a computer algorithm for this
problem we can consider how we might solve a particular example by
hand.
Suppose that we have the given set of marks
55,42,77,63,29,57,89
Algorithm Description
1. Prompt then read the number of marks to be processed.
2. Initialize count to zero.
3. While there are still marks to be processed repeatedly do
a. Read next mark
b. If it is a pass(i.e. >=50) then add one to count.
4. Write out total number of passes.
Pascal implementation
Program passcount (input, output);
Readln (n);
{assert : n>=0}
Count := 0;
I := 0;
While i<n do
Begin {read next mark, test it for pass and update count if
necessary}
I=i+1;
Read(m);
End;
End
Applications: all forms of counting.
Summation
Algorithm Development
The approach we need to take to formulate an algorithm to add n
numbers in a computer is different from what we would do
conventionally to solve the problem.
Conventionally we could write the general equation
S = (a1 + a2 + a3 +…. +an)
We can take a variable named s, set it to 0 and add each number from
given list to s.
The core of the algorithm for summing n numbers therefore involves a
special step followed by a set of n iterative steps.
That is,
1. Compute first sum (s=0) as special case.
2. Build each of the n remaining sums from its predecessor by an
iterative process.
3. Write out the sum of n numbers.
Algorithm description
1. Prompt and read in the number of numbers to be summed.
2. Initialize sum for zero numbers.
3. While less than n numbers have been summed repeatedly do
a. Read in next number
b. Compute current sum by adding the number read to the most
recent sum.
4. Write out sum of n numbers.
Pascal implementation
Program sum (input, output);
Readln (n);
{assert : n>=0}
I := 0;
S :=0.0;
While i<n do
Read (a);
S := s+a;
End;
End
Excercises