Professional Documents
Culture Documents
PPS unit-III PDF
PPS unit-III PDF
PPS unit-III PDF
Objectives
• Demonstrate the use of arrays.
• Understand initialization, declaration of arrays.
• Applications of 1-D and 2-D arrays.
• To understand the software engineering principles of Structured
programming and modularity (top-down development).
• To understand the function declaration, function call, and function
definition.
• To understand inter- function communication through parameters
• To understand the four basic function designs.
• To understand how function communicate through parameters.
• To understand Standard functions.
• To understand the differences between global and local scope.
1
Derived data types
2
Unit No:3
Link to Session
Planner (SP):S.No….of SP
Page No:
• Arrays are useful to process large amounts of data
• For example, suppose we have a temperature reading for each day of the
year and need to manipulate their values several times within a program
• The elements in an array share the same name and are distinguished from one
another by their numbers or subscripts: 0,1,2….. Size-1
An array is homogenous: every value within the array must share the same
data type. In other words, an int array can only hold integers, but not other
data types.
4
How to Create an Array
Element type: what kind of data will the array hold? int, double, char?
Remember, we can only choose one type.
5
Types of Arrays
• Arrays can be classified based on how the data items will be arranged.
16
One Dimensional Array & Declaration
• One dimensional array is a linear list consisting of related and similar data
items.
• In memory, all the data items are stored in contiguous memory locations.
For example:
int number[5];
• Creates an array of 5 integer elements.
7
Unit No:3
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
1. Initializing
• There are four options to initialize one dimensional arrays.
Memory
Layout temp[0] temp[1] temp[2] temp[3] temp [4]
75 79 82 70 68
1000 1002 1004 1006 1008
8
Memory Representation of an Integer Array
9
Operations on one Dimensional Array (2 of 5)
Option B: Initialization without size
int temp [] = {75, 79, 82, 70, 68};
• The compiler allocates memory for an array of 5 elements. The array temp is
initialized as shown below:
temp[0] temp[1] temp[2] temp[3] temp[4]
75 79 82 70 68
1000 1002 1004 1006 1008 Address
temp[0]temp[1] temp[2]temp[3]temp[4]
75 79 82 0 0
1000 1002 1004 1006 1008 Address
For example:
0 0 0 0 0
1000 1002 1004 1006 1008 Address
11
Operations on one Dimensional Array (4 of 5)
2. Inputting values
• Another way to fill the array is to read the values from the keyboard or a file.
• This could be done by using a loop.
Ex:
for(i=0; i<9; i++)
scanf(“%d”,&scores[i]);
3. Accessing elements of an array
• Index is used to access individual elements of an array.
Ex: scores[0];
4. Printing/Output values
• Another common application is printing the contents of an array.
• This can be easily done by using a loop.
Ex.
for(i=0; i<9; i++)
printf(“%d”,scores[i]);
12
Operations on one Dimensional Array (5 of 5)
5. Assigning values to an array
• Suppose we have an array temperature, the readings of the temperature for
the year is represented in the below example .
• The subscripts would be 0, 1, …, 364.
Temperature array
75 79 82 70 68 65 58 63 67 61
temperature[4]
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
Example
• char names[3][4];
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Initializatio Page No:
n
• A two dimensional array can be initialized at the time of declaration:
char names [3][4] = {
{‘J’, 'o', 'h', 'n'},
{‘M’, 'a', 'r', 'y'},
{‘I’, 'v', 'a', 'n'}
};
• An integer array can be initialized to all zeros by using the following
statement:
int nums[3][4] = {0};
• The declaration of a two dimensional array should have the column size
so that ,the elements can be in the form of rows and columns.
2Dexmpl 38 , 2Dexmp 39.c demonstrate 2d array declaration and initialization through turbo c.
16
Multi Dimensional Array
type arrayName[s1][s2][s3]….[sm];
• For example
int a[10][3][2];
• It is represented as “an array of ten arrays of three rows of two
columns”
17
Multi Dimensional Array
3-D Array example.
19
Applications of Arrays
1. Matrix Operations
Addition, multiplication, trace, transpose…etc
• Bubble Sort
• Insertion Sort
• Merge Sort
• etc 20
Unit No:3
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
• Another common operation in computer science is searching, which is the process
Page No:
used to find the location of a target among a list of objects.
• In the case of an array searching means that given a value , we want to find the
location of the first element in the array that contains that value .
• Generally we use the technique only for small lists or lists that are not
searched often.
• In the sequential search , we start searching for the target from the
beginning of the list, and we continue until the we find the target or
either we find it or
1.Easy to understand
2.The list need not be in sorted order
3.If item is at beginning not many comparisons are needed
Disadvantages:
Complexity:
Best case: O(1)
Average case: O(n)
Worst case: O(n)
C program u7_ex6.c
Binary search (1 of 5)
• Sequential search algorithm is very slow if list contains more number of
elements.
• If the array is not sorted ,linear search is the only solution.
• If the list is sorted , we can use a more efficient algorithm called
the binary search.
• We should use a binary search whenever the list starts to become large.
• The binary search starts by testing the data in the element at the middle of the list.
• This determines if the target is in first half or second half of the list.
• If it is in first half , we do not need to check the second half.
• If it is in second half , we do not need to check the first half.
• In other words ,either way we eliminate half the list from further
consideration.
• We repeat this process until we find the target or satisfy ourselves
that it is not in the list.
• To find the middle of the list we three variables,
one to identify the beginning of the list(first)
one to identify the beginning of the list(mid)
one to identify the beginning of the list(last)
mid=( first + last )/2
Binary search Example (2 of 5)
C program u7_ex7.c
Linear Vs Binary Search
Analysis Linear Search Binary Search
36
Unit No:3
Lecture No:L40
Planner (SP):S.No….of SP
Date Conducted:
values.
• Selection Sort
• Bubble Sort
• Insertion Sort
37
Selection Sort (1 of 4)
• The list is divide into two sub lists as sorted and unsorted.
• Find the smallest element from the unsorted sub list and swap it with the
element at the beginning of unsorted sub list.
• After each selection and swapping, the wall between the two sub lists
moves one element ahead, increasing the number of sorted elements and
decreasing the number of unsorted sub lists.
• Move one element from the unsorted sub list to the sorted sub list
completes a sort pass.
Example
39
Selection Sort (3 of 4)
Flowchar
t
40
Selection Sort (4 of 4)
• Code:
• The list is divide into two sub lists as sorted and unsorted.
• The smaller element is bubbled from the unsorted sub list and
moved to the sorted sub list.
• After moving the smallest element to the sorted list, the wall
moves one element ahead, increasing the number of sorted
elements and decreasing the number of unsorted ones.
• Move one element from the unsorted sub list to the sorted sub list
completes one sort pass.
• Thus a list of n elements, the bubble sort requires up to n-1
passes to sort the data.
42
Bubble Sort (2 of 4)
• Example:
43
Bubble Sort (3 of 4)
• Flowchart:
44
Bubble Sort (4 of 4)
Complexity of Bubble_Sort
The complexity of sorting algorithm is
• Code: depends upon the number of comparisons
that are made.
bubblesort ( int A[ ] , int n )
Total comparisons in Bubble sort is
{ n ( n – 1) / 2 ≈ n 2 – n
int i , j, temp ; Complexity = O ( n 2 )
for ( i = 0 ; i < n ; i++ )
{
for ( j = n; j > i ; j - - )
{
if ( A [ j ] < A [ j-1 ] )
{
temp = A [ j ] ;
A[j]=A[j-1];
A [j -1] = temp ;
}
}
}
45 C program u7_ex2.c
Insertion Sort (1 of 4)
• Insertion sort is one of the most common sorting techniques used by card
players.
• The list is divide into two sub lists as sorted and unsorted.
• In each pass, the first element of the unsorted sub list is picked up and
transformed into the sorted sub list by inserting at the appropriate place.
• A list of n elements, the insertion sort requires at most n-1 passes to sort
the data.
46
Insertion Sort (2 of 4)
Example:
47
Insertion Sort (3 of 4)
Flowchart
48
Insertion Sort (4 of 4)
if ( A temp < A [ j ] )
{
A[j+1] = A[j];
j - -;
}//if
else
flag = true;
A[j+1] = temp;
}
}
49 C program u7_ex3.c
Designing Structured Programs
• Simple programs studied so far can be solved and understood without too
much effort.
50
Hierarchy of modularization
51
Modularization
Example:
PRINCIPAL
(main module)
PRESENTATI
TECH QUIZ
ON
(module 3a)
(module 3b) 52
Modular Programming - Manageable
Same book
published in
Huge Book of several volumes.
3000 pages Easily
manageable
Unit No:3
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
• The execution of the program always starts and ends with main, but it can
main function.
54
Structure Chart for a C Program
55
Functions in C
• A function is a section of a program that performs a specific task
• A function receives zero or more pieces of data, operate on them and return at
most one piece of data
56
Advantages of Functions (1 of 2)
• Problems can be factored in to understandable and manageable
steps(easy to code and debug).
57
Advantages of Functions (2 of 2)
Work Allotment
Application Development
58
Function Definition (1 of 4)
• A function is always associated with following three steps
• Function definition
• Function declaration
• Function call
• Function Header
59
Function Definition (2 of 4)
Function Header
• A function header consist of 3 parts
return type
function name
formal parameter list
• A semicolon is not used at end of function definition header
Function Body
• The function body contains local declarations and function statements in
between braces.
• Local declarations specify the variables needed by the function.
• The function statement terminated by a return statement
• If the function return type is void, a return statement is optional.
60
Function Definition (3 of 4)
Parameters
• Formal parameters are variables that are declared in the header of the function
definition
• Actual parameters are used in the calling statement or sometimes they may be
an expression
• Formal and actual parameters must match exactly in type, order, and number.
Their names, however, no need to match.
61
Function Definition (4 of 4)
Parameters
Formal and actual parameters must match exactly in type, order, and number.
Their names, however, need not match.
double average(int x,int y);
void main() actual
{ parameters
double sum1;
sum1=average(10,20);// calling function
} x,y formal
parameters Execute
• Function declaration header consists of three parts: the return type, the
function name and formal parameters
63
Function Declaration (2 of 2)
The general form of a function Prototype or
Declaration
64
Function Call (1 of 4)
• Function call is a postfix expression
• The operand in a function call is the function name; the operator is the
parentheses set (…), which contains actual parameters.
• Actual parameters identify the values that are to be sent to called function and
must match the formal parameters in type and order
• Function call transfers the control to the function definition (called function)
• After execution of the function, it returns the result to the calling function
• Function having a return type void can be used only as a stand-alone statement
65
Function Call (2 of 4)
General form
Actual parameters
66
Function Call (3 of 4)
68
How Functions Work?
main()
User defined
function
Function
call
69
Sample Program with function
70
Sample Program with function
71
Sample Program with function
72
Unit No:3
Lecture No:L42
Planner (SP):S.No….of SP
Date Conducted:
Page No:
• Functions must be both declared and defined.
• Function declaration gives the whole picture of the function .
• Function declaration must be placed before the function call.
• Function definition contains the code that needs to complete the task
73
Declaring, Calling and Defining Functions
74
Basic Function designs (1 of 5)
• Basic function design is based on their return value and parameter list
75
Basic Function designs (1 of 5)
Do not pass argument Do pass arguments
void main(void) void main(void)
{ {
TestFunct(); TestFunct(123);
... ...
} }
81
Unit No:3
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
• A Function whose definitions have been written and are available, which
can be used in a program.
• Function declaration for these functions are grouped together and collected
in several header files
82
Standard Functions (2 of 15 )
Library Functions and the Linker
83
Standard Functions (3 of 15 )
Math functions
• Many important library functions are available for mathematical calculations
• Most of these function declarations are in math header file (math.h) or standard
library header file (stdlib.h )
• Integer functions can be found in stdlib.h
Example
abs(3)=3
abs(-3)=3
fabs(-3.4)=3.4
fabs(1.1)=1.1
abs(-1.9)=1
C example program12.c 85
Standard Functions (5 of 15)
Ceiling Functions
• A ceiling is the smallest integral value greater than or equal to a
number
• If all numbers are considered as a continuous range from minus
infinity to plus infinity, this function moves the number right to an
integral value
• Syntax
double ceil(double number); //math.h
float ceilf(float number); //math.h
long double ceill(long double number); //math.h
• Example
ceil(-1.9) =-1.0 ceil(1.9) =2.0
ceil(1.1) =2.0 ceil(-1.1) =-1.0
Note: ceilf() and ceill() are not supported in the current version
c example program program13.c 53
Standard Functions (6 of 15)
Floor Functions
• A floor is the largest integral value that is less than or equal to a
number
• If all numbers are considered as a continuous range from minus
infinity to plus infinity, this function moves the number left to an
integral value
• Syntax
double floor(double number); //math.h
float floorf(float number); //math.h
long double floorl(long double number); //math.h
• Example
floor(-1.9) =-2.0 floor(1.9) =1.0
floor(1.1) =1.0 floor(-1.1) =-2.0
Note: floorf() and floorl() are not supported in the current version
c example program program14.c 54
Standard Functions (7 of 15)
Truncate Functions
• A Truncate functions return the integral in the direction of zero
• This functions same as floor function for positive numbers and the same as
ceiling for negative numbers
• Syntax
double trunc(double number); //math.h
float truncf(float number); //math.h
long double truncl(long double number); //math.h
• Example
trunc(-1.1) =-1.0
trunc(1.9) =1.0
trunc(2.1) =2.0
trunc(-1.1) =-1.0
Note: trunc() function not supported in the current version 55
Standard Functions (8 of 15)
Round function
• Round function returns nearest integer value
• Syntax:
double round(double number); //math.h
float roundf(float number) //math.h
long double roundl(long double number); //math.h
long int lround(double number); //math.h
long int lroundf(float number) //math.h
long int lroundl(long double number); //math.h
long long int llround(double number); //math.h
long long int llroundf(float number) //math.h
long long int llroundl(long double number); //math.h
• Examples:
round(-1.1)=-1.0 round(1.9)=2.0
round(-1.5)=-2.0 round(1.5)=2.0
56
Standard Functions (9 of 15 )
Power function
• The power(x,y) function returns the value of the x raised to the power of y i.e., x y
• Syntax:
• Example:
pow(3.0,4.0)=81.0
pow(3.4,2.3)=16.687893
90
Standard Functions (10 of 15)
Sqrt function
Sqrt () returns non-negative square root of a number. Error occurs if the number is
negative
Syntax:
Examples:
sqrt(25)=5.0
sqrt(256)=16.0
91
Standard Functions (11 of 15 )
Random numbers
• A random number is a number selected from a set in which all members have
same probability of being selected
• Random numbers are useful in many areas of computer science
• Applications are testing and gaming
Random number Generation:
• Most languages provides functions to generate random numbers
• Each time a function is called, it generates another number
• To generate next number, the function uses its previous number
Random number generation methods
1. Seed provided by the user
2.we can use default seed provided by system
92
Standard Functions (12 of 15 )
Random Number
Generation
93
Standard Functions (13 of 15 )
94
Standard Functions (14 of 15)
Random numbers in C
• Two Random functions are provided in ‘C’ to build a random number series
seed random (srand)
random (rand)
• These function declarations are available in stdlib.h
Syntax
void srand(unsigned int seed);
• To generate same series in each run we can provide a constant seed,
preferably prime number such as 997 Ex: srand(997);
• To generate a different series in each run ,we use time of day as seed
as time will change every second , for this we need time.h
Ex: srand(time(NULL));
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
2. Storage Class
64
SCOPE (1 of 4)
• Scope determines the region of the program in which a defined object is
visible.
1. Block scope
2. Function scope
3. File scope
65
Scope (2 of 4)
Block Scope
• Variables defined within a block have a local scope. They are visible in
that block only. Outside the block they are not visible. Eg:
• { //outer block starts
{//inner block starts
• An object with file scope has visibility through the whole source file in which it is
declared.
• Objects within block scope are excluded from file scope unless specifically
declared to have file scope; in other words, by default, block scope hides
objects from file scope.
• An object with file scope sometimes referred to as a global object and the
variables declared inside this scope are referred to as Global Variables.
• Defines the duration for which the computer allocates memory for the
variable.
69
Linkage
⚫ A large application program may be broken into several modules, with each
module potentially written by a different programmer. Each module is a
separate source file with its own objects.
⚫ We can define two types of linkages:
-internal
-external
⚫ Internal Linkage: An object with an internal linkage is declared and visible in
one module. Other modules cannot refer to this object.
70
Storage Class Specifiers
71
Automatic Variables (1 of 2)
• The default and the most commonly used storage class is automatic.
• When the block is exited, the system releases the memory that was allocated
to the automatic variables, and their values are lost.
72
Automatic Variables (2 of 2)
• Characteristics:
• Scope: block
• Extent: automatic
• Linkage: internal
• Declaration:
auto type variable_name;
• Initialization:
An auto variable can be initialized where it is defined or left uninitialized.
When auto variables are not initialized, its value is a garbage value.
• Register variables specify to the compiler that the variables should be stored
in high-speed memory registers if possible. This is done for efficiency.
• Keep register variables in small local blocks which are reallocated quickly.
74
Register Variables (2 of 2)
• Characteristics:
• Scope: block
• Extent: automatic/register
• Linkage: internal
• Declaration:
• Initialization:
• The static specifier has two different usages depending on its scope.
1. static variable with block scope
2. static variable with file scope.
76
Static Variables (2 of 3)
Static variable with block scope
• When a static variable is declared in a block scope, static defines the extent of the
variable
• Static variables with Block Scope are also known as Static Local Variables
Scope: Block
Extent: Static
Linkage: Internal
• Declaration:
static type variable_name
• Initialization:
• A static variable name can be initialized where it is defined, or it can be left
uninitialized. If it is initialized, it is initialized only once. If not initialized, its
value will be initialized to zero
Scope: File
Extent: Static
Linkage: Internal
Declaration:
Static type variable name;
• Decomposed source files are compiled separately and linked together to form
a unit.
79
External Variables (2 of 2)
• Characteristics:
• Scope: file
• Extent: static
• Linkage: external
• Declaration:
81
C - Scope Rules
81
Unit No:3
Link to Session
Date Conducted:
Page No:
116
Unit No:3
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
Data Flow
Strategies
117
Call by Value & call by Reference(3 of 5)
Downward flow
• Calling function sends data to called function (one way communication)
• Copy of data items are passed from calling function to called function
• Called function may change the values passed, but the original values in the
calling function remains unchanged
• Use call by value mechanism to implement downward flow
• Rules:
a. Use values in function call to pass the data
b. Use appropriate data types in function parameter list to receive data
values
c. Use parameter identifiers in the called function to access the local
copies of the data
118
Call by Value & call by Reference(4 of 5)
Upward flow
• Called function sends data back to the calling function (one way
communication)
• Data items are returned to the calling function from the called function
• Calling function may use the values passed from called function
• Original values of called function remains unchanged
• Use call by reference or return mechanism to implement upward
communication
• Rules:
a. Use &variable name in function call to pass a reference to the variable
b. Use types * in the function parameter list to receive the variable’s address
c. Use *parameter name in the function to reference the original variable
119
Call by Value & call by Reference(5 of 5)
Bi-directional flow
• Rules:
a. Use &variable name in function call to pass a reference to the variable
b. Use types * in the function parameter list to receive the variable’s
address
c. Use *parameter name in the function to reference the original variable
120
Call by Value & call by Reference
‘C’
implementation
• Most programming languages have three strategies for Inter-function
communication: Pass by value, pass by reference and return
1. Pass by values
2. return
121
Call by Value & call by Reference
Downward Communication in
C
• Pass-by-Value is a perfect solution for communication in downward direction
• Two data items are passed from main to the down function.
122
Call by Value & call by Reference
An example for Downward
Communication
125
Call by Value & call by Reference
An example for Upward Communication
127
Call by Value & call by Reference
An example for Bi-directional Communication
128
turbo c example10.c also show error simulation
Call by Value & call by Reference
An Exchange
Function
129
turbo c example11.c also show error simulation
Call by Value & call by Reference
An example for Bi-directional Communication
131
Arrays to functions
Passing Array
Elements
132
Arrays to functions
133
Arrays to functions
Passing the Whole Array
134
Unit No:3
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
• There are two approaches to write repetitive algorithms: one approach uses
loops and the other one uses recursion
86
Designing recursive function
• Every recursive function must have a base case. The statement that solves
the problem is known as the base case.
• The recursion will be done until the problem converges to the simplest
case.
• This simplest case will be solved by the function which will then return a
value.
• Finally, combine the base case and general case into a function.
88
Unit No:3
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
Iterative Definition
•Factorial(n)= 1 if n=0
n*(n-1)*(n-2)…3*2*1 if n>0
Recursive Definition
Base Case
Factorial(n) = 1 if n=0
n*Fcatorial(n-1) if n>0
General Case
89
Recursive representation of Factorial(3) (1 of 2)
90
Recursive representation of Factorial(3) (2 of 2)
factorial(0) = 1;
factorial(n) =
n*factorial(n-1);
factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * ( 2 * (1 * factorial(0)))
= 3 * ( 2 * ( 1 * 1)))
= 3 * ( 2 * 1)
=3*2
=6
91
Recursive representation of Factorial(4) (5 of 11)
Executes factorial(0)
96
The Fibonacci Series
f( 3 )
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
return 1 return 0
Unit No:3
Lecture No:L49
Ackermann’s function
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
Ackermann’s function:
143
Unit No:3
Lecture No:L50
Divide and Conquer sorting methods (1 of 4) Link to Session
Planner (SP):S.No….of SP
Date Conducted:
• We have described 3 sorting techniques – Page No:
• Quick sort ,merge sort and binary search are based on divide and conquer
strategy.
144
Divide and Conquer sorting methods (2 of 4)
• Example: Cutting a circle out of a sheet of paper is a tedious task which takes a
lot of time .
• But there is a way by which we can reduce the time and effort required and cut
145
Divide and Conquer sorting methods (3 of 4)
• Divide and conquer algorithms are quite efficient as the average number of steps in this
methods is less as compared to other procedures.
• Divide and conquer algorithms are more efficient with regard to use of memory caches
Internal and external sorts:
Sorting algorithms are generally classified into 2 types:
1.Internal sorting
2.External sorting
• Internal sort uses only primary memory during entire sorting process.
• All data items are held in the main memory and no secondary memory is required.
• Internal sorting procedures can only process relatively small lists due to memory
constraints
Divide and Conquer sorting methods (4 of 4)
Sorts
Internal Sorts
∙Natural
∙Balanced
Insertion Selection Exchange
∙Polyphase
∙Insertion • selection ∙Bubble
•Sorting large chunks of data requires the use of external or secondary memory.
•An external sort uses a secondary memory such as hard disk, to store data that does not fit
into the main memory
•All external sorts are based on process of merging, different portions of data are sorted
separately and then merged together.
•Depending on the complexity of the list to be sorted, different types of merging procedures
are used in external sorting.
Quick sort (1 of 8)
• Quick sort algorithm was developed by C.A.R Hoare in 1962.
• Like bubble sort quick sort is an exchange sort ,i.e. , items swap positions till the entire
array is sorted.
• The quick sort is more efficient because it requires fewer exchanges to correctly
position an element.
• The basic principle underlying the quick sort algorithm is to pick one element in the array
and rearrange the remaining elements around it.
• The chosen element is called the pivot(usually first element of list).
• Once the pivot is chosen , all the elements lesser than the pivot are moved to the left of
the pivot, and all elements equal to or greater than the pivot are moved to the right of the
pivot.
• The pivot acts as a partition dividing the original lists into two sub lists, and after the
partitioning, the pivot is in its correct position in the sorted list.
• This procedure of choosing the pivot and partitioning the list is recursively applied to the
sub lists till the subsequent sub lists consists of only one element and entire list is
sorted.
148
Quick sort (2 of 8)
Quick sort Algorithm (3 of 8)
1.Start
6.Stop
Quick sort (4 of 8)
Algorithm quicksort(int a[10],int first,int last)
{
i=first; j=last; pivot=first;
if(first<last)
{
while(i<j)
{
while(x[i]<=x[pivot]&&i<last)
Complexity of quick sort: i++;
while(x[j]>x[pivot])
Best case: O(n logn) j--;
if(i<j)
{
Average case:O(n logn) t=x[i]; x[i]=x[j]; x[j]=t;
}
2
Worst case: O(n ) }
t=x[pivot]; x[pivot]=x[j]; x[j]=t;
}
qsort(x,first,j-1);
qsort(x,j+1,last);
}
Quick sort example (5 of 8)
Quick sort (6 of 8)
Quick sort (7 of 8)
Quick sort (8 of 8)
C program u7_ex4.c
Merge sort (1 of 6)
• Merge sort is a divide and conquer external sorting algorithm.
• The basic procedure of merge sort is to divide the list to be sorted into two
smaller sub lists (roughly equal in size) and recursively repeat this
procedure till only one element is left in the sub list.
• After this the various sorted sub lists are merged back to from the parent list
• The merging process also goes on recursively till the sorted original list is
arrived at.
99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
Divide 4 0
Merge sort Example (3 of 6)
0 4 6 15 35 58 86 86 99
6 15 86 99 0 4 35 58 86
6 99 15 86 58 35 0 4 86
99 6 86 15 58 35 86 0 4
Merge 4 0
Merge sort Algorithm (4 of 6)
1.Start
6.Stop
Merge sort Algorithm (5 of 6)
mergesort (a, low, high)
if left >= right return
else
mid ← b(low+high)/2⎦
mergesort(A, low, mid)
mergesort(A, mid+1, high)
merge(a, low, mid, high)
Merge sort Algorithm (6 of 6)
merge(A, low, mid, high)
1. n1 ← mid – low + 1
2. n2 ← high – mid
3. create array L[n1], R[n2]
4. for i ← 0 to n1-1 do L[i] ← A[low +i]
5. for j ← 0 to n2-1 do R[j] ← A[mid+j]
6. k←i←j←0
7. while i < n1 & j < n2
8. if L[i] < R[j]
9. A[k++] ← L[i++]
10. else
11. A[k++] ← R[j++]
12. while i < n1
13. A[k++] ← L[i++]
14. while j < n2
15. A[k++] ← R[j++]
C program u7_ex5.c