Unit 4 PPS Notes
Unit 4 PPS Notes
Introduction
The fundamental data types, namely char, int, float, double are used to store only one value at any
given time.
Hence these fundamental data types can handle limited amounts of data.
In some cases, we need to handle large volume of data in terms of reading, processing and printing.
To process such large amounts of data, we need a powerful data type that would facilitate efficient
storing, accessing and manipulation of data items.
“C” supports a derived data type known as array that can be used for suchapplications.
Arrays:
Types of Arrays:
float b[7];
char c[7];
Like any other variables, arrays must be declared before they are used. The general
The datatype specifies the type of element that will be contained in the array, such as int, float, or char.
The size indicates the maximum number of elements that can be stored inside the array.
Declares the height to be an array containing 50 real elements. Any subscripts 0 to 49 are valid.
int group[10];
To represent a set of five numbers, say (35, 40, 20, 57, 19) by an array variable num. We may declare
the variable num as
int num[5];
Hence the computer reserves five storage locations as shown
num[0] num[1] num[2] num[3] num[4]
num 35 40 20 57 19
num[1] = 40;
num[2] = 20;
num[3] = 57;
num[4] = 19;
Valid Statements:
a = number[0] + 10;
number[4] = number[0] + number[2];
Example-1: Write a program using a single dimensional array to read and display the array elements.
#include<stdio.h>
#include<conio.h>
void main( )
{
int i, x[10];
printf("Enter 10 real numbers: \n");
for (i=0; i <10; i++)
{
scanf(" %d ", &x[i]);
}
printf("The array elements are:"); Output:
for(i=0; i < 10; i++) Enter 10 real numbers: 1 2 3 4 5 6 7 8 9 10
The array elements are: 1 2 3 4 5 6 7 8 9 10
{
printf("%d \t", x[i]);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10],i,small,large;
float sum,avg ;
clrscr();
printf(“ \n Array elements are \n”); for(i=0; i<=9; i++)
scanf(“ %f ”, &a[ i ]);
sum=a[0];
large = a[0];
small = a[0]; Output:
Array elements are: 1 2 3 4 5 6 7 8 9 10
for(i=1; i<=9; i++)
Average is 5.5
{ Largest element in array is 10
sum=sum+a[i]; Smallest element in array is 1
if(a[ i ] > large)
large = a[ i ];
else if( a[ i ] < small)
small = a[ i ];
}
avg=sum/10;
printf(“\n Average is %f \n”, avg);
printf(“\n Largest element in array is %f\n”, large);
printf(“ \n smallest element in array is %f \n”, small);
getch( );
}
Example 3: Given an array of 20 integers. Write a program in C to search for a given integer in that array.
#include<stdio.h>
#include<conio.h>
int main()
{
int a[10],i,n,c=0;
printf("\nEnter the elements of the array: ");
for(i=0; i<=19; i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter the number to be search: ");
scanf("%d",&n);
for(i=0; i<=19; i++)
{
if(a[i]==n)
{
c=1;
break;
}
}
if(c==0)
printf("\nThe %d number is not in the list",n);
else
printf("\nThe %d number is found at postion %d",n,i+1);
return 0;
getch();
} Output:
Enter the elements of the
array: 1
2
3
4
5
5
6
6
7
8
65
1
2
2
3
3
3
5
9
4
Enter the number to be search: 65
The 65 number is found at position 11
Assignment
A two-dimensional array has its elements in a rectangular grid of rows and columns.
The elements of a two-dimensional array can be accessed by using a row index (i.e. row number)
and column index (i.e. column number).
Both the number index and column index are required to select an element of a two-dimensional
array.
A two-dimensional array is popularly known as a matrix.
int a[4][5]={1,5,4,7,5,8};
Example
}
printf("\n");
}
}
(2) Write a program in C to read the elements of the matrix of 3x3 & transpose its element.
# include<stdio.h>
# include<conio.h>
void main( )
{
int i,j, a[3][3], b[3][3];
clrscr( );
printf(“\n Enter Elements of matrix A: \n”);
for( i=0; i < 3; i++)
{
for( j=0; j<3; j++)
{
scanf(“ %d ”, &a[ i ][ j ]);
}
}
/* transposing logic simply copying one matrix elements to another in reverse order */
for( i=0; i < 3; i++)
{
for( j=0; j < 3; j++) Output:
{ Enter Elements of matrix A:
b[ j ][ i ]=a[ i ][ j ]; 3 5 8
} 4 8 5
} 8 5 4
printf(“ \n The Matrix Transpose is \ n”); The Matrix Transpose is
for( i=0; i<3; i++) 3 4 8
{ 5 8 5
for( j=0; j<3; j++) 8 5 4
{
printf(“%d\t”, b[ i ][ j ]);
}
printf (“ \ n”);
}
getch( );
}
(3) Write a program in C to perform addition and subtraction of two matrices of 3X3.
# include<stdio.h>
# include<conio.h>
void main( )
{
int i,j, a[3][3], b[3][3],sum[3][3]={0},subt[3][3]={0};
clrscr( );
printf(“Enter Elements of Matrix of A: \n”);
for( i=0; i < 3; i++)
{
for( j=0; j<3; j++)
{
scanf(“ %d ”, &a[i][j]);
}
}
# include<stdio.h> Output:
# include<conio.h> Enter Element of Matrix of A:
void main( ) 4 5 8
{ 2 9 8
int i,j,k,a[3][3], b[3][3],multi[3][3]={0}; 2 9 4
clrscr( ); Enter Elements of Matrix of B:
printf(“Enter Element of Matrix of A: \n”); 1 3 5
for( i=0; i < 3; i++) 0 5 4
{ 6 7 2
for( j=0; j<3; j++) Matrix Multiplication
{ 52 93 56
scanf(“ %d ”, &a[i][j]); 50 107 62
}
26 79 54
}
printf(“Enter Elements of Matrix of B: \ n”);
for( i=0; i < 3; i++)
{
for( j=0; j < 3; j++)
{
scanf(“ %d ”, &b[i][j]);
}
}
printf(“\n Matrix Multiplication \n”);
getch();
}
C Structures
Structure is a user-defined data type in C language which allows us to combine data of different types
together. Structure helps to construct a complex data type which is more meaningful. It is somewhat
similar to an Array, but an array holds data of similar type only. But structure on the other hand, can
store data of any type, which is practical more useful.
For example: If I have to write a program to store Student information, which will have Student's
name, age, branch, permanent address, father's name etc, which included string values, integer
values etc, how can I use arrays for this problem, I will require something which can hold data of
different types together. In structure, data is stored in form of records.
Defining a structure
struct keyword is used to define a structure. struct defines a new data type which is a collection of
primary and derived datatypes.
Syntax: struct structure_name
{
member variable1;
member variable2;
member variable3;
……..
} structure variables;
As you can see in the syntax above, we start with the struct keyword, then provide your structure a
name, then inside the curly braces, we have to mention all the member variables, which are nothing
but normal C language variables of different types like int, float, array etc.
After the closing curly brace, we can specify one or more structure variables, again this is optional.
Note: The closing curly brace in the structure type declaration must be followed by a semicolon( ;).
Example of Structure
struct Student
char name[25];
int age;
char branch[10];
};
Here struct Student declares a structure to hold the details of a student which consists of 4 data
fields, namely name, age, branch and gender. These fields are called structure elements or
members. each member can have different data type, like in this case, name is an array of char type
and age is of int type etc. Student is the name of the structure and is called as the structure tag.
char name[25];
int age;
char branch[10];
char gender;
};
char name[25];
int age;
char branch[10];
char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student. However this approach is not much recommended.
#include<string.h>
struct Student
char name[25];
int age;
char branch[10];
char gender;
};
int main()
struct Student s1; /* s1 is a variable of Student type and age is a member of Student */
s1.age = 18;
return 0;
Age of Student 1: 18
We can also use scanf() to give values to structure members through terminal.
scanf(" %s ", s1.name);
Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized at compile time.
struct Patient
float height;
int weight;
int age;
};
or,
struct Patient p1;
p1.weight = 73;
p1.age = 23;
Array of Structure
We can also declare an array of structure variables. in which each element of the array will represent
a structure variable. Example : struct employee emp[5];
The below program defines an array emp of size 5. Each element of the array emp is of type Employee.
#include<stdio.h>
struct Employee
char ename[10];
int sal;
};
int i, j;
void ask()
printf("\nEmployee name:\t");
scanf("%s", emp[i].ename);
printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
}
printf("\nDisplaying Employee record:\n");
void main()
ask();
Nested Structures
Nesting of structures, is also permitted in C language. Nested structures means, that one structure
has another stucture as member variable.
Example:
struct Student
char[30] name;
int age;
struct Address
char[50] locality;
char[50] city;
int pincode;
}addr;
};
struct Student
char name[10];
int roll;
};
void main()
printf("\nStudent name:\t");
scanf("%s", std.name);
scanf("%d", &std.roll);
show(std);
}
C Unions
Unions are conceptually similar to structures. The syntax to declare/define a union is
also similar to that of a structure. The only differences are in terms of storage.
In structure each member has its own storage location, whereas all members
of union uses a single shared memory location which is equal to the size of its largest
data member.
This implies that although a union may contain many members of different types, it can
not handle all the members at the same time. A union is declared using
the union keyword.
union item
int m;
float x;
char c;
}It1;
This declares a variable It1 of type union item. This union contains three members
each with a different data type. However only one of them can be used at a time. This is
due to the fact that only one location is allocated for all the union variables, irrespective
of their size. The compiler allocates the storage that is large enough to hold the largest
variable type in the union.
In the union declared above the member x requires 4 bytes which is largest amongst
the members for a 16-bit machine. Other members of union will share the same
memory address.
int a;
float b;
char c;
}t;
t.b;
t.c;
#include <stdio.h>
union item
int a;
float b;
char ch;
};
int main( )
it.a = 12;
it.b = 20.2;
it.ch = 'z';
printf("%d\n", it.a);
printf("%f\n", it.b);
printf("%c\n", it.ch);
return 0;
Output:
-26426
20.1999
As you can see here, the values of a and b get corrupted and only variable c prints the
expected result. This is because in union, the memory is shared among different data
types. Hence, the only member whose value is currently stored will have the memory.
In the above example, value of the variable c was stored at last, hence the value of
other variables is lost.
Enum in C
Enumeration is a user defined datatype in C language. It is used to assign names to the integral
constants which makes a program easy to read and maintain. The keyword “enum” is used to declare
an enumeration.
The enum keyword is also used to define the variables of enum type. There are two ways to define the
variables of enum type as follows.
Example
Live Demo
#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main() {
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur, Fri,
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn, Thur
return 0;
}
Output
The value of enum week: 10 11 12 13 10 16 17
The default value of enum day: 0 1 2 3 18 11 12
In the above program, two enums are declared as week and day outside the main() function. In the
main() function, the values of enum elements are printed.
LINEAR_SEARCH(A, N, VAL)
Step 1: [INITIALIZE] SET POS = -1
Step 2: [INITIALIZE] SET I = 1
Step 3: Repeat Step 4 while I<=N
Step 4: IF A[I] = VAL
SET POS = I
PRINT POS
Go to Step 6
[END OF IF]
SET I = I + 1
[END OF LOOP]
Step 5: IF POS = –1
PRINT “VALUE IS NOT PRESENT IN THE ARRAY”
[END OF IF]
Step 6: EXIT
Binary Search
Binary search is a searching algorithm that works efficiently with a sorted list. The mechanism
of binary search can be better understood by an analogy of a telephone directory. When we are
searching for a particular name in a directory, we first open the directory from the middle and
then decide whether to look for the name in the first part of the directory or in the second part of
the directory. Again, we open some page in the middle and the whole process is repeated until
we finally find the right name.
Take another analogy. How do we find words in a dictionary? We first open the dictionary
somewhere in the middle. Then, we compare the first word on that page with the desired word
whose meaning we are looking for. If the desired word comes before the word on the page, we
look in the first half of the dictionary, else we look in the second half. Again, we open a page in
the first half of the dictionary and compare the first word on that page with the desired word and
repeat the same procedure until we finally get the word. The same mechanism is applied in the
binary search.
Now, let us consider how this mechanism is applied to search for a value in a sorted array.
Consider an array A[] that is declared and initialized as int A[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
and the value to be searched is VAL = 9. The algorithm will proceed in the following manner.
BEG = 0, END = 10, MID = (0 + 10)/2 = 5
Now, VAL = 9 and A[MID] = A[5] = 5
A[5] is less than VAL, therefore, we now search for the value in the second half of the array. So,
we change the values of BEG and MID. Now, BEG = MID + 1 = 6, END = 10, MID = (6 + 10)/2
=16/2 = 8 VAL = 9 and A[MID] = A[8] = 8
A[8] is less than VAL, therefore, we now search for the value in the second half of the segment.
So, again we change the values of BEG and MID.Now, BEG = MID + 1 = 9, END = 10, MID =
(9 + 10)/2 = 9 Now, VAL = 9 and A[MID] = 9.
In this algorithm, we see that BEG and END are the beginning and ending positions of the
segment that we are looking to search for the element. MID is calculated as (BEG + END)/2.
Initially, BEG =lower_bound and END = upper_bound. The algorithm will terminate when
A[MID] = VAL. When the algorithm ends, we will set POS = MID. POS is the position at which
the value is present in the array.However, if VAL is not equal to A[MID], then the values of
BEG, END, and MID will be changed depending on whether VAL is smaller or greater than
A[MID].
(a) If VAL < A[MID], then VAL will be present in the left segment of the array. So, the value of
END will be changed as END = MID – 1.
(b) If VAL > A[MID], then VAL will be present in the right segment of the array. So, the value
of BEG will be changed as BEG = MID + 1.
Finally, if VAL is not present in the array, then eventually, END will be less than BEG. When
this happens, the algorithm will terminate and the search will be unsuccessful.
Figure 14.2 shows the algorithm for binary search.
In Step 1, we initialize the value of variables, BEG, END, and POS. In Step 2, a while loop is
executed until BEG is less than or equal to END. In Step 3, the value of MID is calculated.
In Step 4, we check if the array value at MID is equal to VAL (item to be searched in the array).
If a match is found, then the value of POS is printed and the algorithm exits. However, if a match
is not found, and if the value of A[MID] is greater than VAL, the value of END is modified,
otherwise if A[MID] is greater than VAL, then the value of BEG is altered. In Step 5, if the value
of POS = –1, then VAL is not present in the array and an appropriate message is printed on the
screen before the algorithm exits.
BUBBLE SORT
Bubble sort is a very simple method that sorts the array elements by repeatedly moving the
largest element to the highest index position of the array segment (in case of arranging elements
in ascending order). In bubble sorting, consecutive adjacent pairs of elements in the array are
compared with each other. If the element at the lower index is greater than the element at the
higher index, the two elements are interchanged so that the element is placed before the bigger
one. This process will continue till the list of unsorted elements exhausts.This procedure of
sorting is called bubble sorting because elements ‘bubble’ to the top of the list. Note that at the
end of the first pass, the largest element in the list will be placed at its proper position (i.e., at the
end of the list).
Note If the elements are to be sorted in descending order, then in first pass the smallest element is moved
to the highest index of the array.
Technique
The basic methodology of the working of bubble sort is given as follows:
(a) In Pass 1, A[0] and A[1] are compared, then A[1] is compared with A[2], A[2] is compared
with A[3], and so on. Finally, A[N–2] is compared with A[N–1]. Pass 1 involves n–1
comparisons and places the biggest element at the highest index of the array.
(b) In Pass 2, A[0] and A[1] are compared, then A[1] is compared with A[2], A[2] is compared
with A[3], and so on. Finally, A[N–3] is compared with A[N–2]. Pass 2 involves n–2
comparisons and places the second biggest element at the second highest index of the array.
(c) In Pass 3, A[0] and A[1] are compared, then A[1] is compared with A[2], A[2] is compared
with A[3], and so on. Finally, A[N–4] is compared with A[N–3]. Pass 3 involves n–3
comparisons and places the third biggest element at the third highest index of the array.
(d) In Pass n–1, A[0] and A[1] are compared so that A[0]<A[1]. After this step, all the elements
of the array are arranged in ascending order.
Example: To discuss bubble sort in detail,let us consider an array A[] that has the following
elements:
A[] = {30, 52, 29, 87, 63, 27, 19, 54}
Pass 1:
(a) Compare 30 and 52. Since 30 < 52, no swapping is done.
(b) Compare 52 and 29. Since 52 > 29, swapping is done.
30, 29, 52, 87, 63, 27, 19, 54
(c) Compare 52 and 87. Since 52 < 87, no swapping is done.
(d) Compare 87 and 63. Since 87 > 63, swapping is done.
30, 29, 52, 63, 87, 27, 19, 54
(e) Compare 87 and 27. Since 87 > 27, swapping is done.
30, 29, 52, 63, 27, 87, 19, 54
(f) Compare 87 and 19. Since 87 > 19, swapping is done.
30, 29, 52, 63, 27, 19, 87, 54
(g) Compare 87 and 54. Since 87 > 54, swapping is done.
30, 29, 52, 63, 27, 19, 54, 87
Observe that after the end of the first pass, the largest element is placed at the highest index of
the array. All the other elements are still unsorted.
Pass 2:
(a) Compare 30 and 29. Since 30 > 29, swapping is done.
29, 30, 52, 63, 27, 19, 54, 87
(b) Compare 30 and 52. Since 30 < 52, no swapping is done.
(c) Compare 52 and 63. Since 52 < 63, no swapping is done.
(d) Compare 63 and 27. Since 63 > 27, swapping is done.
29, 30, 52, 27, 63, 19, 54, 87
(e) Compare 63 and 19. Since 63 > 19, swapping is done.
29, 30, 52, 27, 19, 63, 54, 87
(f) Compare 63 and 54. Since 63 > 54, swapping is done.
29, 30, 52, 27, 19, 54, 63, 87
Observe that after the end of the second pass, the second largest element is placed at the second
highest index of the array. All the other elements are still unsorted.
Pass 3:
(a) Compare 29 and 30. Since 29 < 30, no swapping is done.
(b) Compare 30 and 52. Since 30 < 52, no swapping is done.
(c) Compare 52 and 27. Since 52 > 27, swapping is done.
29, 30, 27, 52, 19, 54, 63, 87
(d) Compare 52 and 19. Since 52 > 19, swapping is done.
29, 30, 27, 19, 52, 54, 63, 87
(e) Compare 52 and 54. Since 52 < 54, no swapping is done.
Observe that after the end of the third pass, the third largest element is placed at the third highest
index of the array. All the other elements are still unsorted.
Pass 4:
(a) Compare 29 and 30. Since 29 < 30, no swapping is done.
(b) Compare 30 and 27. Since 30 > 27, swapping is done.
29, 27, 30, 19, 52, 54, 63, 87
(c) Compare 30 and 19. Since 30 > 19, swapping is done.
29, 27, 19, 30, 52, 54, 63, 87
(d) Compare 30 and 52. Since 30 < 52, no swapping is done.
Observe that after the end of the fourth pass, the fourth largest element is placed at the fourth
highest index of the array. All the other elements are still unsorted.
Pass 5:
(a) Compare 29 and 27. Since 29 > 27, swapping is done.
27, 29, 19, 30, 52, 54, 63, 87
(b) Compare 29 and 19. Since 29 > 19, swapping is done.
27, 19, 29, 30, 52, 54, 63, 87
(c) Compare 29 and 30. Since 29 < 30, no swapping is done.
Observe that after the end of the fifth pass, the fifth largest element is placed at the fifth highest
index of the array. All the other elements are still unsorted.
Pass 6:
(a) Compare 27 and 19. Since 27 > 19, swapping is done.
19, 27, 29, 30, 52, 54, 63, 87
(b) Compare 27 and 29. Since 27 < 29, no swapping is done.
Observe that after the end of the sixth pass, the sixth largest element is placed at the sixth largest
index of the array. All the other elements are still unsorted.
Pass 7:
(a) Compare 19 and 27. Since 19 < 27, no swapping is done.
Figure 14.6 shows the algorithm for bubble sort. In this algorithm, the outer loop is for the total
number of passes which is N–1. The inner loop will be executed for every pass. However, the
frequency of the inner loop will decrease with every pass because after every pass, one element
will be in its correct position. Therefore, for every pass, the inner loop will be executed N–I
times, where N is the number of elements in the array and I is the count of the pass.
BUBBLE_SORT(A, N)
Step 1: Repeat Step 2 For 1 = to N-1
Step 2: Repeat For J = to N - I
Step 3: IF A[J] > A[J + 1]
SWAP A[J] and A[J+1]
[END OF INNER LOOP]
[END OF OUTER LOOP]
Step 4: EXIT
Figure 14.6 Algorithm for bubble sort
Write a program to enter n numbers in an array. Redisplay the array with elements being
sorted in ascending order.
#include <stdio.h>
#include <conio.h>
void main()
{
int i, n, temp, j, arr[10];
clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf("\n Enter the elements: ");
for(i=0; i<n; i++)
{
scanf("%d", &arr [i]);
}
for(i=0; i<n; i++)
{
for(j=0; j<n–i–1; j++)
{
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
printf("\n The array sorted in ascending order is :\n");
for(i=0;i<n;i++)
printf("%d\t", arr[i]);
getch();
}
Output
Enter the number of elements in the array : 10
Enter the elements : 8 9 6 7 5 4 2 3 1 10
The array sorted in ascending order is :
1 2 3 4 5 6 7 8 9 10
INSERTION SORT
Insertion sort is a very simple sorting algorithm in which the sorted array (or list) is built one
element at a time. We all are familiar with this technique of sorting, as we usually use it for
ordering a deck of cards while playing bridge.
The main idea behind insertion sort is that it inserts each item into its proper place in the final
list. To save memory, most implementations of the insertion sort algorithm work by moving
the current data element past the already sorted values and repeatedly interchanging it with the
preceding value until it is in its correct place. Insertion sort is less efficient as compared to other
more advanced algorithms such as quick sort, heap sort, and merge sort.
Technique
Insertion sort works as follows:
• The array of values to be sorted is divided into two sets. One that stores sorted values and
another that contains unsorted values.
• The sorting algorithm will proceed until there are elements in the unsorted set.
• Suppose there are n elements in the array. Initially, the element with index 0 (assuming LB
=0) is in the sorted set. Rest of the elements are in the unsorted set.
• The first element of the unsorted partition has array index 1 (if LB = 0).
• During each iteration of the algorithm, the first element in the unsorted set is picked up and
inserted into the correct position in the sorted set.
Initially, A[0] is the only element in the sorted set. In Pass 1, A[1] will be placed either before or
after A[0], so that the array A is sorted. In Pass 2, A[2] will be placed either before A[0], in
between A[0] and A[1], or after A[1]. In Pass 3, A[3] will be placed in its proper place. In Pass
N–1, A[N–1] will be placed in its proper place to keep the array sorted. To insert an element
A[K] in a sorted list A[0], A[1], ..., A[K–1], we need to compare A[K] with A[K–1], then with
A[K–2], A[K–3], and so on until we meet an element A[J] such that A[J] <= A[K]. In order to
insert A[K] in its correct position, we need to move elements A[K–1],A[K–2], ..., A[J] by one
position and then A[K] isinserted at the (J+1)th location. The algorithm for insertion sort is given
in Fig. 14.7.In the algorithm, Step 1 executes a for loop which will be repeated for each element
in the array. In Step 2, we store the value of the Kth element in TEMP. In Step 3, we set the Jth
index in the array. In Step 4, a for loop is executed that will create space for the new element
from the unsorted list to be stored in the list of sorted elements. Finally, in Step 5, the element is
stored at the (J+1) th location.
INSERTION-SORT (ARR, N)
Step 1: Repeat Steps 2 to 5 for K = 1 to N – 1
Step 2: SET TEMP = ARR[K]
Step 3: SET J = K - 1
Step 4: Repeat while TEMP <= ARR[J]
SET ARR[J + 1] = ARR[J]
SET J = J - 1
[END OF INNER LOOP]
Step 5: SET ARR[J + 1] = TEMP
[END OF LOOP]
Step 6: EXIT
Figure 14.7 Algorithm for insertion sort
Advantages of Insertion Sort: The advantages of this sorting algorithm are as follows:
• It is easy to implement and efficient to use on small sets of data.
• It can be efficiently implemented on data sets that are already substantially sorted.
• It performs better than algorithms like selection sort and bubble sort. Insertion sort
algorithmis simpler than shell sort, with only a small trade-off in efficiency. It is over twice
as fast as the bubble sort and almost 40 per cent faster than the selection sort.
• it requires less memory space (only O(1) of additional memory space).
• It is said to be online, as it can sort a list as and when it receives new elements.
The algorithm for selection sort is shown in Fig. 14.8. In the algorithm, during the Kth pass, we
need to find the position POS of the smallest elements from ARR[K], ARR[K+1], ..., ARR[N].
To find the smallest element, we use a variable SMALL to hold the smallest value in the sub-
array ranging from ARR[K] to ARR[N]. Then, swap ARR[K] with ARR[POS]. This procedure
is repeated until all the elements in the array are sorted.
1. Bubble sort
2. Insertion sort
3. Selection sort
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping
the adjacent elements if they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5
> 1.
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm
does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is
completed. The algorithm needs one whole pass without any swap to know it is
sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
#include<stdio.h>
#include<conio.h>
void main()
int A[20], i, j, c, n;
clrscr();
printf("How many numbers do you want to sort by Bubble Sort:");
scanf("%d",&n);
printf("\n Enter %d numbers: ",n);
for(i=0;i<n;i++)
scanf("%d",&A[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(A[j]>A[j+1])
{
c=A[j];
A[j]=A[j+1];
A[j+1]=c;
}
}
}
printf("\n Sorted array is \n");
for(i=0;i<n;i++)
printf("%d ",A[i]);
getch();
}
Output:
Enter 10 numbers: 2 10 9 8 4 3 1 7 5 6
Sorted array is
1 2 3 4 5 6 7 8 9 10
Insertion Sort
Insertion sort is a simple sorting algorithm that works the way we sort playing
cards in our hands.
C Program to sort an array in ascending order using Insertion Sort
#include <stdio.h>
void main()
{
int n, i, j, temp;
int arr[64];
1. Write an algorithm for Bubble sort. Explain its working for sorting 16,
23,12,2,43,60,54.
3. Write down the difference between Bubble sort and insertion sort with
example.
Notion of order of complexity: There are three notation used to describe the complexity of an
algorithm as stated below:
1. BIG O NOTATION:
If we have two different algorithms to solve the same problem where one algorithm executes in
10 iterations and the other in 20 iterations, the difference between the two algorithms is not
much. However, if the first algorithm executes in 10 iterations and the other in 1000 iterations,
then it is a matter of concern.
This factor is called efficiency of the algorithm and denoted by Big O, and is expressed as O(n).
The Big O notation, where O stands for ‘order of’, is concerned with what happens for very large
values of n. For example, if a sorting algorithm performs n2 operations to sort just n elements,
then that algorithm would be described as an O(n2) algorithm. If f(n) and g(n) are the functions
defined on a positive integer number n, then f(n) = O(g(n)) That is, f of n is Big–O of g of n if
and only if positive constants c and n exist, such that f(n) ≤ cg(n).
It means that for large amounts of data, f(n) will grow no more than a constant factor than g(n).
Hence, g provides an upper bound. Note that here c is a constant. The Big O notation provides a
strict upper bound for f(n). This means that the function f(n) can do better but not worse than the
specified value. Big O notation is simply written as f(n) ∈ O(g(n)) or as f(n) = O(g(n))
2. OMEGA NOTATION (Ω):
The Omega notation provides a tight lower bound for f(n). This means that the function can
never do better than the specified value but it may do worse.
Ω notation is simply written as, f(n) ∈ Ω(g(n)), where n is the problem size and
Ω(g(n)) = {h(n): ∃ positive constants c > 0, n0 such that 0 ≤ cg(n) ≤ h(n), ∀ n ≥ n0}.
Hence, we can say that Ω(g(n)) comprises a set of all the functions h(n) that are greater than
or equal to cg(n) for all values of n ≥ n0.
3. THETA NOTATION (Q):
Theta notation provides an asymptotically tight bound for f(n). Θ notation is simply written as,
f(n) ∈ Θ(g(n)), where n is the problem size and Θ(g(n)) = {h(n): ∃ positive constants c1, c2, and
n0 such that 0 ≤ c1g(n) ≤ h(n) ≤ c2g(n), ∀ n ≥ n0}.
Hence, we can say that Θ(g(n)) comprises a set of all the functions h(n) that are between c1g(n)
and c2g(n) for all values of n ≥ n0.