Chapter 3s ALGO
Chapter 3s ALGO
Chapter 3s ALGO
Chapter Three
It is very difficult to select a sorting algorithm over another. And there is no sorting algorithm
better than all others in all circumstances. Some sorting algorithm will perform well in some
situations, so it is important to have a selection of sorting algorithms. Some factors that play an
important role in selection processes are the time complexity of the algorithm (use of computer
time), the size of the data structures (for E.g. an array) to be sorted (use of storage space), and the
time it takes for a programmer to implement the algorithms (programming effort).
For example, a small business that manages a list of employee names and salary could easily use
an algorithm such as bubble sort since the algorithm is simple to implement and the data to be
sorted is relatively small. However a large public limited with ten thousands of employees
experience horrible delay, if we try to sort it with bubble sort algorithm. More efficient
algorithm, like Heap sort is advisable.
a. Bubble Sort
In bubble sort, each element is compared with its adjacent element. If the first element is larger
than the second one, then the positions of the elements are interchanged, otherwise it is not
changed. Then next element is compared with its adjacent element and the same process is
repeated for all the elements in the array until we get a sorted array.
Let A be a linear array of n numbers. Sorting of A means rearranging the elements of A so that
they are in order. Here we are dealing with ascending order. i.e., A[1] < A[2] < A[3] < ...... A[n].
Suppose the list of numbers A[1], A[2], ………… A[n] is an element of array A. The bubble sort
algorithm works as follows:
Step 1: Compare A[1] and A[2] and arrange them in the (or desired) ascending order, so that
A[1] < A[2].that is if A[1] is greater than A[2] then interchange the position of data by
1
Complied By Mr. Abraham W
Data structure and Algorithms For 2nd Year Computer Science
swap=A[1]; A[1] = A[2]; A[2] = swap. Then compare A[2] and A[3] and arrange them so that
A[2] < A[3]. Continue the process until we compare A[N – 1] with A[N].
Note: Step1 contains n – 1 comparison i.e., the largest element is “bubbled up” to the nth
position or “sinks” to the nth position. When step 1 is completed A[N] will contain the largest
element.
Step 2: Repeat step 1 with one less comparisons that is, now stop comparison at A [n – 1] and
possibly rearrange A[N – 2] and A[N – 1] and so on.
Note: in the first pass, step 2 involves n–2 comparisons and the second largest element will
occupy A[n-1]. And in the second pass, step 2 involves n – 3 comparisons and the 3rd largest
element will occupy A[n – 2] and so on.
Step n – 1: compare A[1]with A[2] and arrange them so that A[1] < A[2]
After n – 1 step, the array will be a sorted array in increasing (or ascending) order.
The following figures will depict the various steps (or PASS) involved in the sorting of an array
of 5 elements. The elements of an array A to be sorted are: 42, 33, 23, 74, and 44
Thus the sorted array is 23, 33, 42, 44, and 74.
ALGORITHM
Let A be a linear array of n numbers. Swap is a temporary variable for swapping (or interchange)
the position of the numbers.
1. Input n numbers of an array A
2. Initialize i = 0 and repeat through step 4 if (i < n)
3. Initialize j = 0 and repeat through step 4 if (j < n – i – 1)
4. If (A[j] > A[j + 1])
(a) Swap = A[j]
(b) A[j] = A[j + 1]
(c) A[j + 1] = Swap
5. Display the sorted numbers of array A
2
Complied By Mr. Abraham W
Data structure and Algorithms For 2nd Year Computer Science
6. Exit.
Program to implement bubble sort using arrays static memory allocation coded and compiled
in Borland C++
#include<iostream.h>
#define MAX 20
void main()
{
int arr[MAX],i,j,k,temp,n,xchanges;
cout<<"Enter the number of elements : ";
cin>>n;
for (i = 0; i < n; i++)
{
cout<<"Enter element"<<(i+1)<<":";
cin>>arr[i];
}
cout<<"Unsorted list is :\n";
for (i = 0; i < n; i++)
cout<<arr[i];
cout<<"\n";
for (i = 0; i < n-1 ; i++)
{
xchanges=0;
for (j = 0; j <n-1-i; j++)
{
if (arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
xchanges++;
}}
if (xchanges==0)
break;
cout<<"After Pass"<<(i+1)<<"elements are :";
for (k = 0; k < n; k++)
cout<<arr[k]<<",";
cout<<"\n";
}
cout<<"Sorted list is :";
for (i = 0; i < n; i++)
cout<<arr[i]<<",";
}
Exercise: Write C++ Program to implement bubble sort using dynamic memory allocation that
can be coded and compiled in Borland C++
3
Complied By Mr. Abraham W
Data structure and Algorithms For 2nd Year Computer Science
b. Selection Sort
Selection sort algorithm finds the smallest element of the array and interchanges it with the
element in the first position of the array. Then it finds the second smallest element from the
remaining elements in the array and places it in the second position of the array and so on.
Let A be a linear array of ‘n’ numbers, A [1], A [2], A [3] ... A [n].
Step 1: Find the smallest element in the array of n numbers A[1], A[2], ...... A[n]. Let LOC is the
location of the smallest number in the array. Then interchange A[LOC] and A[1]by swap =
A[LOC]; A[LOC] = A[1]; A[1] = Swap.
Step 2: Find the second smallest number in the sub list of n – 1 elements A [2] A [3]...... A [n –
1] (first element is already sorted). Now we concentrate on the rest of the elements in the array.
Again A [LOC] is the smallest element in the remaining array and
LOC the corresponding location then interchange A [LOC] and A [2].Now A [1] and A [2] is
sorted, since A [1] less than or equal to A [2].
Step 3: Repeat the process by reducing one element each from the array
Step n – 1: Find the n – 1 smallest number in the sub array of 2 elements (i.e., A(n–1), A (n)).
Consider A [LOC] is the smallest element and LOC is its corresponding position.
Then interchange A [LOC] and A(n – 1). Now the array A [1], A [2], A [3], A [4]…A [n] will be
a sorted array.
Following figure is generated during the iterations of the algorithm to sort 5 numbers
42, 33, 23, 74, 44:
Algorithm
Let A be a linear array of n numbers A [1], A [2], A [3] … A [k], A [k+1]… A [n]. Swap be a
temporary variable for swapping (or interchanging) the position of the numbers. Min is the
variable to store smallest number and Loc is the location of the smallest element.
1. Input n numbers of an array A
2. Initialize i = 0 and repeat through step5 if (i < n – 1)
(a) min = a[i]
(b) loc = i
3. Initialize j = i + 1 and repeat through step 4 if (j < n – 1)
4. if (a[j] < min)
4
Complied By Mr. Abraham W
Data structure and Algorithms For 2nd Year Computer Science
Program to implement selection sort using static memory allocation that is using arrays coded
and compiled in Borland C++
#include<iostream.h>
#define MAX 20
void main()
{
int arr[MAX], i,j,k,n,temp,smallest;
cout<<"Enter the number of elements :";
cin>>n;
for (i = 0; i < n; i++)
{
cout<<"Enter element "<<(i+1)<<":";
cin>>arr[i];
}
cout<<"Unsorted list is :";
for (i = 0; i < n; i++)
cout<<arr[i];
cout<<"\n";
for (i = 0; i < n-1 ; i++)
{
smallest = i;
for(k = i + 1; k < n ; k++)
{
if (arr[smallest] > arr[k])
smallest = k ;
}
if ( i != smallest )
{
temp = arr [i];
arr[i] = arr[smallest];
arr[smallest] = temp ;
}
cout<<"After Pass "<<(i+1)<<" elements are :";
for (j = 0; j < n; j++)
cout<<arr[ j];
cout<<"\n";
5
Complied By Mr. Abraham W
Data structure and Algorithms For 2nd Year Computer Science
}
cout<<"Sorted list is :";
for (i = 0; i < n; i++)
cout<<arr[i];
}
Exercise: Write C++ Program to implement selection sort using dynamic memory allocation that
can be coded and compiled in Borland C++
c. Insertion Sort
Insertion sort algorithm sorts a set of values by inserting values into an existing sorted file.
Compare the second element with first, if the first element is greater than second; place it before
the first one. Otherwise place is just after the first one. Compare the third value with second. If
the third value is greater than the second value then place it just after the second. Otherwise place
the second value to the third place. And compare third value with the first value. If the third
value is greater than the first value place the third value to second place, otherwise place the first
value to second place. And place the third value to first place and so on.
Let A be a linear array of n numbers A [1], A [2], A [3] ... A[n]. The algorithm scans the array A
from A [1] to A [n], by inserting each element A[k], into the proper position of the previously
sorted sub list. A [1], A [2], A [3] ... A [k – 1]
Step 1: As the single element A [1] by itself is sorted array.
Step 2: A [2] is inserted either before or after A [1] by comparing it so that A[1], A[2] is sorted
array.
Step 3: A [3] is inserted into the proper place in A [1], A [2], that is A [3] will be compared with
A [1] and A [2] and placed before A [1], between A [1] and A
[2], or after A [2] so that A [1], A [2], A [3] is a sorted array.
Step 4: A [4] is inserted in to a proper place in A [1], A [2], A [3] by comparing it; so that A [1],
A [2], A [3], A [4] is a sorted array.
Step 5: Repeat the process by inserting the element in the proper place in array
Step n: A [n] is inserted into its proper place in an array A [1], A [2], A [3] ... A [n –1] so that A
[1], A [2], A [3]... A [n] is a sorted array.
Algorithm
Let A be a linear array of n numbers A [1], A [2], A [3], ...... ,A [n]......Swap be a temporary
variable to interchange the two values. Pos is the control variable to hold the position of each
pass.
1. Input an array A of n numbers
2. Initialize i = 1 and repeat through steps 4 by incrementing i by one.
(a) If (i < = n – 1)
(b) Swap = A [I],
(c) Pos = i – 1
3. Repeat the step 3 if (Swap < A[Pos] and (Pos >= 0))
(a) A [Pos+1] = A [Pos]
(b) Pos = Pos-1
4. A [Pos +1] = Swap
5. Exit
6
Complied By Mr. Abraham W
Data structure and Algorithms For 2nd Year Computer Science
Program to implement insertion sort using arrays coded and compiled in Borland C++
#include<iostream.h>
#define MAX 20
void main()
{
int arr[MAX],i,j,k,n;
cout<<"Enter the number of elements : ";
cin>>n;
for (i = 0; i < n; i++)
{
cout<<"Enter element :"<<(i+1);
cin>>arr[i];
}
cout<<"Unsorted list is :";
for (i = 0; i < n; i++)
cout<<arr[i];
cout<<"\n";
for(j=1;j < n;j++)
{
k=arr[j]; /*k is to be inserted at proper place*/
for(i=j-1;i>=0 && k<arr[i];i--)
arr[i+1]=arr[i];
arr[i+1]=k;
cout<<"Pass"<<j<<"Element inserted in proper place:";
for (i = 0; i < n; i++)
cout<<arr[i];
cout<<"\n";
}
cout<<"Sorted list is :";
for (i = 0; i < n; i++)
cout<<arr[i];
}
3.2 Simple Searching Algorithms
7
Complied By Mr. Abraham W
Data structure and Algorithms For 2nd Year Computer Science
In linear search, each element of an array is read one by one sequentially and it is compared with
the desired element. A search will be unsuccessful if all the elements are read and the desired
element is not found.
Let A be an array of n elements, A[1],A[2],A[3], ...... A[n]. “data” is the element to be searched.
Then this algorithm will find the location “loc” of data in A. Set loc = – 1, if the search is
unsuccessful.
1. Input an array A of n elements and “data” to be searched and initialize loc = – 1.
2. Initialize i = 0; and repeat through step 3 if (i < n) by incrementing i by one.
3. If (data = A[i])
(a) loc = i
(b) GOTO step 4
4. If (loc > 0)
(a) Display “data is found and searching is successful”
5. Else
(a) Display “data is not found and searching is unsuccessful”
6. Exit
Program to implement sequential searching coded and compiled using Borland C++
#include<iostream.h>
void main()
{
char opt;
int arr[20],n, i, item;
cout<<"enter number of elements you want:";
cin>>n;
for(i=0; i < n;i++)
{
cout<<"Enter element"<<i+1<<":";
cin>>arr[i];
}
cout<<"Press any key to continue....\n";
//getch();
do
{
cout<<"Enter the element to be searched : ";
cin>>item; //Input the item to be searched
for(i=0;i< n;i++)
{
if (item == arr[i])
{
cout<<"An item "<<item<<"found at position"<<i+1;
8
Complied By Mr. Abraham W
Data structure and Algorithms For 2nd Year Computer Science
break;
}
}/*End of for*/
if (i == n)
cout<<"Item not found in array",item;
cout<<"Press (Y/y) to continue :";
//fflush(stdin);
cin>>opt;
}while(opt == 'Y'&& opt != 'y');
}
b. Binary Search
Binary search is an extremely efficient algorithm when it is compared to linear search. Binary
search technique searches “data” in minimum possible comparisons. Suppose the given array is a
sorted one, otherwise first we have to sort the array elements.
Then apply the following conditions to search a “data”.
1. Find the middle element of the array (i.e., n/2 is the middle element if the array or the
sub-array contains n elements).
2. Compare the middle element with the data to be searched, then there are following
three cases.
(a) If it is a desired element, then search is successful.
(b) If it is less than desired data, then search only the first half of the array, i.e.,
the elements which come to the left side of the middle element.
(c) If it is greater than the desired data, then search only the second half of the
array, i.e., the elements which come to the right side of the middle element.
Repeat the same steps until an element are found or exhaust the search area.
9
Complied By Mr. Abraham W
Data structure and Algorithms For 2nd Year Computer Science
Following steps are generated if we binary search a data = 45 from the above array.
Step 1:
LB = 0; UB = 6
mid = (0 + 6)/2 = 3
A[mid] = A[3] = 30
Step 2:
Since (A[3] < data) - i.e., 30 < 45 - reinitialize the variable LB, UB and mid
LB = 3 UB = 6
mid = (3 + 6)/2 = 4
A[mid] = A[4] = 40
Step 3:
Since (A[4] < data) - i.e., 40 < 45 - reinitialize the variable LB, UB and mid
LB = 4 UB = 6
mid = (4 + 6)/2 = 5
A[mid] = A[5] = 45
Step 4:
10
Complied By Mr. Abraham W
Data structure and Algorithms For 2nd Year Computer Science
Program to implement the binary search coded and compiled using Borland C++
#include<iostream.h>
void main()
{
char opt;
int arr[20],start,end,middle,n,i,item;
cout<<"How many elements you want to enter in the array :";
cin>>n;
for(i=0; i < n; i++)
{
cout<<"Enter element"<<(i+1)<<":";
cin>>arr[i];
}
cout<<"Press any key to continue...";
do
{
cout<<"Enter the element to be searched : ";
cin>>item;
start=0;
end=n-1;
middle=(start + end)/2;
while(item != arr[middle] && start <= end)
{
if (item > arr[middle])
start=middle+1;
else
end=middle-1;
middle=(start+end)/2;
}
if (item==arr[middle])
cout<<"found at position "<<middle + 1;
if (start>end)
cout<<" not found in array"<<item;
cout<<"Pree (Y/y) to continue : ";
cin>>opt;
}while(opt == 'Y' || opt == 'y');
}
11
Complied By Mr. Abraham W