Sunteți pe pagina 1din 78

MODULE V – SEARCHING AND SORTING

1. MODULE INTRODUCTION
The students are already familiar with various types of linear and non-linear data
structures and their practical applications. Students may have already felt the need
for searching and sorting the data stored using various data structures. Catering to
this need, this chapter makes the students familiar with various methods for sorting
and searching. The merits and demerits of each sorting and searching method are
to be brought to the attention of the students. The concepts included in this chapter
may be transacted through the learning strategies such as discussion, seminar, as-
signment, lab work, illustration, output prediction, laboratory demonstration and
showcasing. Also, the teachers can utilize activities like error correction and
program development for evaluation.

2. CONTENT DETAILS
Searching: Linear Search – Binary Search – Comparison of searching algorithms

Sorting: Insertion sort – Bubble sort –– Selection sort – Heap sort – Quick sort –
Merge sort – Comparison of sorting algorithms.

3. UNIT OUTCOME

• Familiarize and understand the need for searching and sorting in real life
computing applications.
• Integrate the features and facilities of various searching and sorting algorithms
to develop software for real life applications.

1
4. MODULE COMPETENCIES
1. Apply searching algorithms to real life problems
2. Apply sorting algorithms to real life problems.

5. INSTRUCTIONAL OBJECTIVES
C5: Understand, analyze for efficiency and implement search algorithms:
Linear and Binary
C5G1: Linear search
C5G1S1: Basic concepts
TI1: How does linear search works in a list implemented as an
array?
TI2: How does linear search works in a list implemented as a linked
list?
TI3: Demonstrate the working of linear search to find a given
element in a list implemented as an array.
TI4: Demonstrate the working of linear search to find a given
element in a list implemented as linked list.
TI5: Analyse best, worst and best case timing complexity of the
linear search
C5G1S2: Implementation
TI1: Write a program to implement linear search algorithm for
searching a number in a list of numbers maintained as an array.
TI2: Write a program to implement linear search algorithm for
searching a name in a list of name maintained as a 2-D array.

2
TI3: Write a program to implement linear search algorithm for
searching a number in a list of numbers maintained as a linked
list.
TI4: Write a program to implement linear search algorithm for
searching a name in a list of name maintained as a linked list.
C5G1: Binary search
C5G1S1: Basic concepts
TI1: How does Binary search works in a list implemented as an
array?
TI2: Can Binary search works in a list implemented as a linked list?
Justify.
TI3: Demonstrate the working of Binary search to find a given
element in a list implemented as an array.
TI4: Analyse best, worst and best case timing complexity of the
Binary search
C5G1S2: Implementation
TI1: Write a program to implement Binary search algorithm for
searching a number in a list of numbers maintained as an array.
TI2: Write a program to implement Binary search algorithm for
searching a name in a list of name maintained as a 2-D array.
TI3: Write a program to implement Binary search algorithm for
searching a number in a list of numbers maintained as a linked
list.
C6: Understand, analyze for efficiency and implement sorting algorithms: Insertion
sort, Bubble sort, Selection Sort, Quick sort, Heap sort and Merge sort
C5G1: Insertion, Bubble, Selection, Quick, Heap and Merge sorts

3
C5G1S1: Basic concepts of Insertion, Bubble, Selection, Quick, Heap
and Merge sorts
TI1: How Insertion, Bubble, Selection, Quick, Heap and Merge sorts
work with a list of numbers maintained as an array?
TI2: How Insertion, Bubble, Selection, Quick, Heap and Merge sorts
work with a list of numbers maintained as a linked list?
TI3: Demonstrate the working of Insertion, Bubble, Selection,
Quick, Heap and Merge sorts with a list of numbers
implemented as an array.
TI4: Demonstrate the working of Insertion, Bubble, Selection,
Quick, Heap and Merge sorts with a list of numbers
implemented as a linked list.
TI5: Analyse best, worst and best case timing complexity of
Insertion, Bubble, Selection, Quick, Heap and Merge sorts.
TI6: Compare the performance of the Insertion, Bubble, Selection,
Quick, Heap and Merge sorts with each other.
TI7: What are the merits and demerits of each of the Insertion,
Bubble, Selection, Quick, Heap and Merge sorts?
C5G1S1: Implementation
TI1: Write a program to sort a list of numbers maintained as an array
using Insertion, Bubble, Selection, Quick, Heap and Merge
sorts
TI2: Write a program to sort a list of names maintained as an array
using Insertion, Bubble, Selection, Quick, Heap and Merge
sorts

4
TI3: Write a program to sort a list of student records maintained as
an array of structures using Insertion, Bubble, Selection, Quick,
Heap and Merge sorts
TI4: Write a program to sort a list of numbers maintained as a linked
list using Insertion, Bubble, Selection, Quick, Heap and Merge
sorts
TI5: Write a program to sort a list of names maintained as a linked
list using Insertion, Bubble, Selection, Quick, Heap and Merge
sorts
TI6: Write a program to sort a list of student records maintained as a
linked list of structures using Insertion, Bubble, Selection,
Quick, Heap and Merge sorts

5
CONCEPT MAP OF THE MODULE

7. INSTRUCTIONAL MATERIAL
7.1. SEARCHING AND SORTING
Sorting and searching are fundamental operations in computer science. Sorting
refers to the operation of arranging data in some given order, such as increasing or
decreasing, with numerical data or alphabetically, with character data. Searching

6
refers to the operation of finding the location of a given item in a collection of
items.
Sorting and searching frequently apply to files. A file is a collection of records,
each record having one or more fields. The fields used to distinguish among the
records are known as keys. Sorting the file F refers to sorting F with respect to a
particular primary key, and searching in F refers to searching for the records with a
given key value. The association between a record and its key may be simple or
complex. In the simple form, the key is contained within the record at a specific
offset from the start of the record. Such a record is called an internal key or an
embedded key. In other cases, there is a separate table of keys that includes
pointers to the records. Such keys are external.
For every file there is at least one set of keys (possibly more) that is unique (that is,
no two records have the same key value). Such a key is called primary key. For
example, if the file is stored as an array, the index within the array of an element is
a unique external key for that element. However, since any field of record can
serve as the key in a particular application, key need not always be unique. For
example, in a file of names and addresses if the name is used as the key for a
particular search, it will probably not be unique, since there may be two records
with the same name in a file. Such key is called a secondary key.
There are many sorting and searching algorithms. The particular algorithm one
chooses depends on the properties of the data, the location where it resides and the
operations one may perform on data. The data may be an array of records, a linked
list, a tree or even a graph. Because different sorting and searching techniques may
be suitable for different file organizations, a file is often designed with a specific
search technique in mind. The file to be searched or sorted may be contained
completely in memory, completely in auxiliary memory or it may be divided
between the two. Sorting or searching in which the entire file is constantly in
memory are called internal searching/sorting, whereas those in which most of the
file is kept in auxiliary storage is external sorting/searching. We concentrate
primarily on internal sorting and searching.

7.2. SEARCHING
Searching is an operation which finds the location of a given element in a list.
Suppose DATA is a list maintained in memory. Searching finds the location LOC
in memory of some given ITEM of information or sends some message that ITEM
does not belong to DATA. The search is said to be successful or unsuccessful
depending on whether the ITEM does or does not belong to DATA. Here, we will
discuss two standard searching methods – linear and binary search.

7
7.2. 1. LINEAR SEARCH
Linear search, also known as sequential search, is the simplest method of searching
and is suitable for searching a set of data for a particular value. The search is
applicable to list organized either as a sorted or unsorted array or linked list.
Suppose a linear array data contains n elements, and suppose a specific item of
information is given. We want either to find the location loc of item in the array
data or to send some message to indicate that item does not appear in data. Linear
search operates by checking every element of a list until a match is found. Linear
search runs in O(n). If the data are distributed randomly, on average n/2
comparisons will be needed. The best case is that the value is equal to the first
element tested, in which case only 1 comparison is needed. The worst case is that
the value is not in the list, in which case n comparisons are needed.
An algorithm of the linear search is given below:
int linear_search(int *data, int length, int value)
{ for(int i = 0 ; i < length ; i++)
if(data[i] == value) return 1 ;
return 0 ;
}
The complete C++ implementation of linear search for a list of numbers
maintained as an array is given below.
//Program that searches for a given
//number using linear search method in
//an unsorted array
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
const int MAX=50;
class array
{ private:
int arr[MAX]; int count;
public:
array()
{count=0;}
void add(int);
void display(void);
int search(int);
};
//adds a new element to the array

8
void array::add(int item)
{ if(count<MAX)
{ arr[count]=item; count++; }
else
cout<<"\nArray is full"<<endl;
}
//Display the elements in the list
void array::display(void)
{ cout<<"There are "<<count<<" elements in the list"<<endl;
cout<<"They are :"<<endl<<endl;
for(int i=0;i<count;i++)
cout<<arr[i]<<" ";
}
//finds for given element in an array
int array::search(int num)
{ for(int i=0;i<count;i++)
if(arr[i]==num) return i;
return -1;
}
void main()
{ int element,n,i,c;
array linear;
while(1)
{ clrscr(); gotoxy(20,10);
cout<<"Perform the Linear Search";
gotoxy(20,11);
cout<<"------------------------"<<endl;
gotoxy(20,12);
cout<<"1. Input data into the list";
gotoxy(20,13);
cout<<"2. Display data in the list";
gotoxy(20,14);
cout<<"3. Search an item in the list";
gotoxy(20,15);
cout<<"4. Exit from program";
do
{ gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<"";
}

9
while((c<1)||(c>4));
if(c==4)exit(1);
clrscr();
switch(c)
{ case 1:
clrscr();
cout<<"How many elements: ";
cin>>n;
cout<<endl<<endl;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1<<" : ";
cin>>element;
linear.add(element);
}
break;
case 2:
clrscr();linear.display();break;
case 3:
clrscr();
cout<<"Enter number to search:";
cin>>element;
i=linear.search(element);
if(i==-1)
cout<<"Element" <<element << " is not present in the list.";
else
cout<<"The element "<< element<<"is at position" <<i+1
<<" in the list.";
cout<<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}

The following program illustrates the linear search in a list of numbers maintained
as a header linked list.

#include <iostream.h>
#include<conio.h>

10
#include<stdlib.h>
class array
{ private :
struct node
{ int data; node *link; }*start;
public :
array();
~array();
void add(int);
void display(void);
int search(int);
};
//Initializes count of elements maintained //in the header node
array::array()
{ start= new node;
start->link=NULL;
start->data=0;
}
//Deallocates memory
array::~array()
{ node *current;
while(start!=NULL)
{ current=start->link;
delete current;
start=current;
}
}
//Insert element
void array::add(int val)
{ node *current;
start->data++;
current = new node;
current->link = start->link;
current->data=val;
start->link=current;
}
//Displays the contents of the list
void array::display()
{ node *current;
cout<<"There are "<<start->data <<" elements in the list"<<endl

11
<<"They are: " <<endl;
for(current=start->link; current; current=current->link)
cout<<current->data<<" ";
}
// Search for an item
int array::search(int num)
{ node *current;
int c=0;
for(current=start;current != NULL; current=current->link)
{ c++;
if(current->data==num) return c;
}
return -1;
}
void main()
{ int element,n,i,c;
array linear;
while(1)
{ clrscr();
gotoxy(20,10);
cout<<"Perform the Linear Search";
gotoxy(20,11);
cout<<"------------------------"<<endl;
gotoxy(20,12);
cout<<"1. Input data into the list";
gotoxy(20,13);
cout<<"2. Display data in the list";
gotoxy(20,14);
cout<<"3. Search an item in the list";
gotoxy(20,15);
cout<<"4. Exit from program";
do
{ gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<"";
}
while((c<1)||(c>4));
if(c==4)exit(1);
clrscr();
switch(c)

12
{ case 1:
clrscr();
cout<<"How many elements: ";
cin>>n;
cout<<endl<<endl;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1<<" : ";
cin>>element;
linear.add(element);
}
break;
case 2:
clrscr();linear.display();break;
case 3:
clrscr();
cout<<"Enter number to search for: ";
cin>>element;
i=linear.search(element);
if(i==-1)
cout<<"Element “<<element << “ is not present in the list.";
else
cout<<"Element " <<element <<"is at position "<<i+1
<<" in the list.";
cout<<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}
The following program illustrates the linear search in a sequential file containing
employee records.
#include<fstream.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<iomanip.h>
class employee

13
{ private:
char emplname[20];
char emplcode[6];
char desig[20];
int salary;
public:
void add(void);
void display(void);
void search(void);
};
void employee::add(void)
{ char choice;
fstream file("employee.dat", ios::app|ios::out);
if(file.fail())
{ cout<<"Error in Opening the file employee.dat";
exit(1);
}
do
{ clrscr();
gotoxy(10,3);
cout<<"Enter the Following Details ";
gotoxy(10,4);
cout<<"---------------------------";
gotoxy(10,6);
cout<<"Employee Name : ";
gotoxy(10,7);
cout<<"Employee Code : ";
gotoxy(10,8);
cout<<"Designation : ";
gotoxy(10,9);
cout<<"Salary : ";
cin.ignore(1);
gotoxy(27,6);
cin.getline(emplname,20);
gotoxy(27,7);
cin.getline(emplcode,10);
gotoxy(27,8);
cin.getline(desig,20);
gotoxy(27,9);
cin>>salary;

14
file<<emplname<<endl<<emplcode <<endl<<desig<<endl<<salary <<endl;
cin.ignore(1);
do
{ gotoxy(20,12);
cout<<"Add More (y/n): ";
cin.get(choice);
if((toupper(choice)!='Y')&& (toupper(choice)!='N'))
{ gotoxy(35,12);
cout<<" Invalid Data";
}
}
while((toupper(choice)!='Y')&& (toupper(choice)!='N'));
}
while((toupper(choice)=='Y'));
file.close();
}
void employee::display(void)
{ int i;
fstream file("employee.dat",ios::in);
if(file.fail())
{ cout<<"Error in Opening the file employee.dat";
exit(1);
}
clrscr();
cout<<"Employee Name\t Empl. Code\tDesignation\t Salary" <<endl;
for(i=0;i<70;++i) cout<<'-';
cout<<endl;
while(!file.eof())
{ file.getline(emplname,20);
file.getline(emplcode,10);
file.getline(desig,20);
file>>salary;
file.ignore(1);
if(file.eof()) break;
cout.width(20);
cout<<setiosflags(ios::left) <<emplname;
cout.width(10);
cout<<emplcode;
cout.width(20);
cout<<desig;

15
cout.width(6);
cout<<setiosflags(ios::right) <<salary<<endl;
}
for(i=0;i<70;++i)cout<<'-';
file.close();
}
void employee::search(void)
{ char no[10],choice;
do
{ clrscr();
gotoxy(10,1);
cout<<"Enter Employee code whose details to be displayed: ";
cin>>no;
int flag=0;
fstream file("employee.dat",ios::in);
if(file.fail())
{ cout<<"Error in Opening the file employee.dat";
exit(1);
}
while(!file.eof())
{ file.getline(emplname,20);
file.getline(emplcode,10);
file.getline(desig,20);
file>>salary;
file.ignore(1);
if(file.eof()) break;
if(strcmpi(emplcode,no)==0)
{ flag=1;
gotoxy(10,1);
cout<<"Details of the employee with employee code " <<no;
gotoxy(10,2);
cout<<"-------------------------------------------------";
gotoxy(10,4);
cout<<"Employee Name : " <<emplname;
gotoxy(10,5);
cout<<"Employee Code : " <<emplcode;
gotoxy(10,6);
cout<<"Designation : " <<desig;
gotoxy(10,7);
cout<<"Salary : " <<salary;

16
gotoxy(10,8);
}
}
file.close();
if(flag==0)
{ gotoxy(20,5);
cout<<"This record does not exist"<<endl;
}
cin.ignore(1);
do
{ gotoxy(20,18);
cout<<"Search More (y/n): ";
cin.get(choice);
if((toupper(choice)!='Y')&& (toupper(choice)!='N'))
{ gotoxy(39,18);
cout<<" Invalid Data";
}
}
while((toupper(choice)!='Y')&& (toupper(choice)!='N'));
}
while((toupper(choice)=='Y'));
}
void main()
{ int c;
employee e;
while (1)
{ clrscr();
gotoxy(20,10);
cout<<"Linear Search in an Employee Database";
gotoxy(20,11);
cout<<"-------------------------------------"<<endl;
gotoxy(20,12);
cout<<"1. Build an Employee File";
gotoxy(20,13);
cout<<"2. List the Contents of the Employee File";
gotoxy(20,14);
cout<<"3. Search for the Details of an Employee";
gotoxy(20,15);
cout<<"4. Exit from Program";
do

17
{ gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<" ";
}
while((c<1) || (c>4));
if (c==4) exit(1);
clrscr();
switch(c)
{ case 1:
e.add();break;
case 2:
e.display();break;
case 3:
e.search();break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}

7.2.2. BINARY SEARCH


Binary search method is very fast and efficient technique for finding a particular
value in a linear array, by "ruling out" half of the data at each step. This method
requires that the list of elements be in sorted order. A binary search finds the
middle element of the list and makes a comparison to determine whether the
middle element is equal, greater than or less than the desired value. If they are
equal, the search has been completed successfully. If the middle element is greater
than the item being searched for, the search process is repeated in the first half of
the array. Otherwise, the process is repeated in the second half. A binary search is
an example of a divide and conquer algorithm. Note that each time a comparison is
made, the number of elements yet to be searched is cut in half. For large arrays,
this method is superior to the sequential search in which each comparison reduces
the number of elements yet to be searched by only one. Because of the division of
the list to be searched into two equal parts, this search method is called the binary
search.
The most common application of binary search is to find a specific value in a
sorted list. The search begins by examining the value in the centre of the list;
because the values are sorted, it then knows whether the value occurs before or
after the centre value, and searches through the correct half in the same way.

18
Binary search executes in O(log n) time. It is considerably faster than a linear
search. It can be implemented using recursion or iteration, as shown below,
although in many languages it is more elegantly expressed recursively.
Here is simple recursive pseudo code which determines the index of a given value
in a sorted list arr between indices lower and upper:
function BinarySearch(arr, item, lower, upper)
if upper < lower
return not found
mid = floor((lower+upper)/2)
if arr[mid] = item
return mid
if item < arr[mid]
return BinarySearch(arr, item, lower, mid-1)
else
return BinarySearch(a, item, mid+1, upper)
This recursive algorithm can be rewritten using loops, as shown below:
function BinarySearch(arr, item, lower, upper)
while lower ≤ upper
mid = floor((lower+upper)/2)
if arr[mid] = item
return mid
if item < arr[mid]
upper = mid-1
else
lower = mid+1
return not found
In both cases, the algorithm terminates because on each recursive call or iteration,
the range of indexes upper minus lower always gets smaller, and so must
eventually become negative.
Examples: An example of binary search in action is a simple guessing game in
which a player has to guess a positive integer selected by another player between 1
and N, using only questions answered with yes or no. Supposing N is 16 and the
number 11 is selected, the game might proceed as follows.
• Is the number greater than 8? (Yes)
• Is the number greater than 12? (No)
• Is the number greater than 10? (Yes)
• Is the number greater than 11? (No)

19
Therefore, the number must be 11. At each step, we choose a number right in the
middle of the range of possible values for the number. For example, once we know
the number is greater than 8, but less than or equal to 12, we know to choose a
number in the middle of the range [9, 12] (either 10 or 11 will do). At most log2
N questions are required to determine the number, since each question halves the
search space. Note that one less question (iteration) is required than for the general
algorithm, since the number is constrained to a particular range.
Even if the number we're guessing can be arbitrarily large, in which case there is
no upper bound N, we can still find the number in at most 2 log2 k steps (where k
is the (unknown) selected number) by first finding an upper bound by repeated
doubling. For example, if the number were 11, we could use the following
sequence of guesses to find it:
• Is the number greater than 1? (Yes)
• Is the number greater than 2? (Yes)
• Is the number greater than 4? (Yes)
• Is the number greater than 8? (Yes)
• Is the number greater than 16? (No, N=16, proceed as above)
• (We know the number greater than 8 )
• Is the number greater than 12? (No)
• Is the number greater than 10? (Yes)
• Is the number greater than 11? (No)
The following program illustrates the iterative binary search applied to a list
maintained as a sorted array.
//Program that searches for a given
//number using binary search method in a
//sorted array
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
const int MAX=50;
class array
{ private:
int arr[MAX]; int count;
public:
array()
{count=0;}
void add(int);
void display(void);

20
int search(int);
void sort(void);
};
//adds a new element to the array
void array::add(int item)
{ if(count<MAX)
{ arr[count]=item; count++;}
else
cout<<"\nArray is full"<<endl;
}
//Display the elements in the list
void array::display(void)
{ cout<<"There are "<<count<<" elements in the list"<<endl;
cout<<"They are :"<<endl<<endl;
for(int i=0;i<count;i++)
cout<<arr[i]<<" ";
}
//Sort the array
void array::sort(void)
{ for(int i=0;i<count-1;i++)
for(int j=0;j<(count-i-1);j++)
if(arr[j]>arr[j+1])
{ int t=arr[j]; arr[j]=arr[j+1];
arr[j+1]=t;
}
return;
}
//finds for given element in an array
int array::search(int num)
{ int mid,lower=0,upper=count-1;
for(mid=(lower+upper)/2; lower<=upper; mid=(lower+upper)/2)
{ if(arr[mid]==num) return mid;
if(arr[mid]>num) upper=mid-1;
else
lower=mid+1;
}
return -1;
}
void main()
{ int element,n,i,c;

21
array binary;
while(1)
{ clrscr();
gotoxy(20,10);
cout<<"Perform the Binary Search";
gotoxy(20,11);
cout<<"------------------------"<<endl;
gotoxy(20,12);
cout<<"1. Input data into the list";
gotoxy(20,13);
cout<<"2. Display data in the list";
gotoxy(20,14);
cout<<"3. Search an item in the list";
gotoxy(20,15);
cout<<"4. Exit from program";
do
{ gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<"";
}
while((c<1)||(c>4));
if(c==4)exit(1); clrscr();
switch(c)
{ case 1:
clrscr();
cout<<"How many elements: ";
cin>>n;
cout<<endl<<endl;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1<<" : ";
cin>>element;
binary.add(element);
}
break;
case 2:
clrscr(); binary.sort();
binary.display(); break;
case 3:
clrscr(); binary.sort();
cout<<"Enter number to search:";

22
cin>>element;
i=binary.search(element);
if(i==-1)
cout<<"Number is not present in the array.";
else
cout<<"The element " <<element << "is at position " <<i+1
<<" in the list.";
cout<<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}
The following program illustrates the recursive version of the binary search applied
to a list maintained as a sorted array.
//Program that searches for a given number using binary search method in a
//sorted array
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
const int MAX=50;
class array
{ private:
int arr[MAX]; int count;
public:
array()
{count=0;}
void add(int);
void display(void);
int search(int, int, int);
void sort(void);
int getcount(void)
{ return count; }
};
//adds a new element to the array
void array::add(int item)
{ if(count<MAX)

23
arr[count++]=item;
else
cout<<"\nArray is full"<<endl;
}
//Display the elements in the list
void array::display(void)
{ cout<<"There are "<<count<<" elements in the list"<<endl;
cout<<"They are :"<<endl<<endl;
for(int i=0;i<count;i++)
cout<<arr[i]<<" ";
}
//Sort the array
void array::sort(void)
{ for(int i=0;i<count-1;i++)
for(int j=0;j<(count-i-1);j++)
if(arr[j]>arr[j+1])
{ int t=arr[j]; arr[j]=arr[j+1];
arr[j+1]=t;
}
return;
}
//finds for given element in an array
int array::search(int num, int lower, int upper)
{ if(upper<lower) return -1;
int mid=floor((lower+upper)/2);
if(arr[mid]==num) return mid;
else
if(arr[mid]<num)
search(num,lower,mid-1);
else
search(num,mid+1,upper);
}
void main()
{ int element,n,i,c;
array binary;
while(1)
{ clrscr(); gotoxy(20,10);
cout<<"Perform the Binary Search";
gotoxy(20,11);
cout<<"-------------------------" << endl;

24
gotoxy(20,12);
cout<<"1. Input data into the list";
gotoxy(20,13);
cout<<"2. Display data in the list";
gotoxy(20,14);
cout<<"3. Search an item in the list";
gotoxy(20,15);
cout<<"4. Exit from program";
do
{gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<"";
}
while((c<1)||(c>4));
if(c==4)exit(1); clrscr();
switch(c)
{ case 1:
clrscr();
cout<<"How many elements: ";
cin>>n; cout<<endl<<endl;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1<<" : ";
cin>>element;
binary.add(element);
}
break;
case 2:
clrscr(); binary.sort();
binary.display(); break;
case 3:
clrscr(); binary.sort();
cout<<"Enter number to search:";
cin>>element;
i=binary.search(element,0, binary.getcount()-1);
if(i==-1)
cout<<"Element "<<element <<" is not present in the list.";
else
cout<<"The element " <<element<<" is at position "
<<i+1<<" in the list.";
cout<<endl;

25
break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}
The following program illustrates the binary search applied to a file. The content of
the file is maintained in a sorted array for searching.
//Applying binary search to a file
#include<fstream.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<iomanip.h>
const int MAX=20;
class employee
{ private:
struct empl
{ char emplname[20];
char emplcode[6];
char desig[20];
int salary;
} arr[MAX];
int emplcount;
public:
employee()
{ emplcount=0;}
void add(void);
void display(void);
void search(void);
void sort(void);
};
void employee::add(void)
{ char choice;
fstream file("employee.dat",ios::out);
if(file.fail())
{ cout<<"Error in Opening the file employee.dat";
exit(1);

26
}
do
{ clrscr();
gotoxy(10,3);
cout<<"Enter the Following Details";
gotoxy(10,4);
cout<<"---------------------------";
gotoxy(10,6);
cout<<"Employee Name : ";
gotoxy(10,7);
cout<<"Employee Code : ";
gotoxy(10,8);
cout<<"Designation : ";
gotoxy(10,9);
cout<<"Salary : ";
cin.ignore(1);
gotoxy(27,6);
cin.getline (arr[emplcount].emplname, 20);
gotoxy(27,7);
cin.getline (arr[emplcount].emplcode, 10);
gotoxy(27,8);
cin.getline(arr[emplcount].desig,20);
gotoxy(27,9);
cin>>arr[emplcount].salary;
cin.ignore(1);
do
{ gotoxy(20,12);
cout<<"Add More (y/n): ";
cin.get(choice);
if((toupper(choice)!='Y')&& (toupper(choice)!='N'))
{ gotoxy(35,12);
cout<<" Invalid Data";
}
}
while((toupper(choice)!='Y')&& (toupper(choice)!='N'));
emplcount++;
}
while((toupper(choice)=='Y'));
for(int i=0;i<emplcount;i++)
file<<arr[i].emplname<<endl <<arr[i].emplcode<<endl <<arr[i].desig

27
<<endl <<arr[i].salary<<endl;
file.close();
}
void employee::display(void)
{ int i=0;
fstream file("employee.dat",ios::in);
if(file.fail())
{ cout<<"Error in Opening the file employee.dat";
exit(1);
}
clrscr();
while(!file.eof())
{ file.getline(arr[i].emplname,20);
file.getline(arr[i].emplcode,10);
file.getline(arr[i].desig,20);
file>>arr[i].salary;
file.ignore(1);
if(file.eof()) break;
i++;
}
emplcount=i;
cout<<"Employee Name\tEmpl.Code \tDesignation\t Salary" <<endl;
for(i=0;i<70;++i) cout<<'-';
cout<<endl;
for(i=0;i<emplcount;i++)
{ cout.width(20);
cout<<setiosflags(ios::left) <<arr[i].emplname;
cout.width(10);
cout<<arr[i].emplcode;
cout.width(20);
cout<<arr[i].desig;
cout.width(6);
cout<<setiosflags(ios::right) <<arr[i].salary<<endl;
}
for(i=0;i<70;++i)cout<<'-';
file.close();
}
//Sort the array
void employee::sort(void)
{ for(int i=0;i<emplcount-1;i++)

28
for(int j=0;j<(emplcount-i-1);j++)
if(arr[j].emplcode> arr[j+1].emplcode)
{ empl t=arr[j]; arr[j]=arr[j+1];
arr[j+1]=t;
}
return;
}
void employee::search(void)
{ char no[10],choice;
fstream file("employee.dat",ios::in);
if(file.fail())
{ cout<<"Error in Opening the file employee.dat";
exit(1);
}
int i=0;
while(!file.eof())
{ file.getline(arr[i].emplname,20);
file.getline(arr[i].emplcode,10);
file.getline(arr[i].desig,20);
file>>arr[i].salary;
file.ignore(1);
if(file.eof()) break;
i++;
}
file.close();
emplcount=i;
do
{ clrscr(); gotoxy(10,1);
cout<<"Enter Employee code whose details to be displayed: ";
cin>>no;
int flag=0;
for(i=0;i<emplcount;i++)
{ if(strcmpi(arr[i].emplcode,no)==0)
{ flag=1; gotoxy(10,1);
cout<<"Details of the employee with employee code "<<no;
gotoxy(10,2);
cout<<"-------------------------------------------------";
gotoxy(10,4);
cout<<"Employee Name : " <<arr[i].emplname;
gotoxy(10,5);

29
cout<<"Employee Code : " << arr[i].emplcode;
gotoxy(10,6);
cout<<"Designation : " <<arr[i].desig;
gotoxy(10,7);
cout<<"Salary : " <<arr[i].salary;
gotoxy(10,8);
}
}
if(flag==0)
{ gotoxy(20,5);
cout<<"This record does not exist"<<endl;
}
cin.ignore(1);
do
{ gotoxy(20,18);
cout<<"Search More (y/n): ";
cin.get(choice);
if((toupper(choice)!='Y')&& (toupper(choice)!='N'))
{ gotoxy(39,18);
cout<<" Invalid Data";
}
}
while((toupper(choice)!='Y')&& (toupper(choice)!='N'));
}
while((toupper(choice)=='Y'));
}
void main()
{ int c;
employee e;
while (1)
{ clrscr();
gotoxy(20,10);
cout<<"Linear Search in an Employee Database";
gotoxy(20,11);
cout<<"-------------------------------------" <<endl;
gotoxy(20,12);
cout<<"1. Build an Employee File";
gotoxy(20,13);
cout<<"2. List the Contents of the Employee File";
gotoxy(20,14);

30
cout<<"3. Search for the Details of an Employee";
gotoxy(20,15);
cout<<"4. Exit from Program";
do
{ gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<" ";
}
while((c<1) || (c>4));
if (c==4) exit(1); clrscr();
switch(c)
{ case 1:
e.add(); break;
case 2:
e.sort(); e.display();
break;
case 3:
e.sort(); e.search(); break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}

7.3. SORTING
Sorting means arranging a set of data in some order. There are different methods
that are used to sort the data in ascending or descending order. These sorting
algorithms are broadly classified into two categories: internal and external sorting.
If all the data that is to be sorted can be accommodated at a time in memory then
internal sorting methods are used. When the data to be sorted is so large that some
of the data is present in the memory and some is kept in auxiliary memory, then
external sorting methods are used. Here, we mainly concentrate on internal sorting
methods.
There are different types of internal sorting methods. Some sorting algorithms are
simple and intuitive, such as the bubble sort. Others, such as quick sort, are
extremely complicated, but produce lightening-fast results.
Sorting algorithms are often classified by:

31
• Computational complexity (worst, average and best behaviour) in terms of the
size of the list (n). For typical sorting algorithms good behaviour is O(n
• log
• n) and bad behaviour is O(n2). Ideal behaviour for a sort is O(n). Sort
algorithms which only use an abstract key comparison operation always need at
least O(n
• log
• n) comparisons on average.
• Memory usage (and use of other computer resources). In particular, some
sorting algorithms are "in place", such that little memory is needed beyond the
items being sorted, while others need to create auxiliary locations for data to be
temporarily stored.
• Stability: Stable sorting algorithms maintain the relative order of records with
equal keys (i.e. values). That is, a sorting algorithm is stable if whenever there
are two records R and S with the same key and with R appearing before S in the
original list, R will appear before S in the sorted list.
• Whether or not they are a comparison sort. A comparison sort examines the
data only by comparing two elements with a comparison operator.
• General method: insertion, exchange, selection, merging, etc. Exchange sorts
include bubble sort and quick sort. Selection sorts include heap sort.
When equal elements are indistinguishable, such as with integers, stability is not an
issue. However, assume that the following pairs of numbers are to be sorted by
their first coordinate:
(4, 1) (3, 1) (3, 7) (5, 6)
In this case, two different results are possible, one which maintains the relative
order of records with equal keys, and one which does not:
(3, 1) (3, 7) (4, 1) (5, 6) (Order maintained)
(3, 7) (3, 1) (4, 1) (5, 6) (Order changed)
Unstable sorting algorithms may change the relative order of records with equal
keys, but stable sorting algorithms never do so. Unstable sorting algorithms can be
specially implemented to be stable. One way of doing this is to artificially extend
the key comparison, so that comparisons between two objects with otherwise equal
keys are decided using the order of the entries in the original data order as a tie-
breaker. Remembering this order, however, often involves an additional space cost.

32
Some of commonly used internal sorting methods are discussed here.

7.3.1. INSERTION SORT


Insertion sort is a simple comparison type sorting algorithm that is relatively
efficient for small lists and mostly-sorted lists, and often is used as part of more
sophisticated algorithms. It works by taking elements from the list one by one and
inserting them in their correct position into a new sorted list.
In abstract terms, each iteration of the insertion sort removes an element from the
input data, inserting it at the correct position in the already sorted list, until no
elements are left in the input. The choice of which element to remove from the
input is arbitrary and can be made using almost any choice algorithm. Sorting is
typically done in-place. The result array after k iterations contains the first k entries
of the input array and is sorted. In each step, the first remaining entry of the input
is removed, inserted into the result at the right position.
To save memory, most implementations use an in-place sort that works by sharing
the array’s space for storing both the sorted new list and the remaining unsorted
elements. But insertion is expensive, requiring shifting all following elements over
by one.
Insertion sort is much less efficient on large lists than the more advanced
algorithms such as quick sort, heap sort, or merge sort, but it has various
advantages:
• Simple to implement
• Efficient on (quite) small data sets
• Efficient on data sets which are already substantially sorted
• More efficient in practice than most other simple O(n2) algorithms such as
selection sort or bubble sort: the average time is n2/4 and it is linear in the best
case
• Stable (does not change the relative order of elements with equal keys)
• In-place (only requires a constant amount O(1) of extra memory space)
• It is an online algorithm, in that it can sort a list as it receives it. (An online
algorithm is one that can process its input piece-by-piece, without having the
entire input available from the start. In contrast, an offline algorithm is given the
whole problem data from the beginning and is required to output an answer,
which solves the problem at hand. For example, selection sort requires that the
entire list is given before it can sort it.)

33
Example: The first iteration starts with comparison of 1st element with 0th element.
In the second iteration 2nd element is compared with the 0th and 1st elements. In
general, each iteration compares an element with all elements before it. During
comparison if it is found that the elements in question can be inserted at a suitable
position then space is created for it by shifting the other elements one position to
the right and inserting the element at the suitable position. This procedure is
repeated for all the elements in the array. This procedure is illustrated below for an
array that contains 5 elements.
In the first iteration, the 1st element 17 is compared with the 0th element 25. Since
17 is smaller than 25, 17 is inserted at 0th place. The 0th element 25 is shifted one
position to the right. In the second iteration, the 2nd element and 0th element 17 are
compared. Since 31 is greater than 17, nothing is done. Then the 2nd element 31 is
compared with the 1st element 25. Again no action is taken as 25 is less than 31. In
the third iteration, the 3rd element 13 is compared with the 0th element 17. Since, 13
is smaller than 17, 13 is inserted at 0th place in the array and all the elements from
0th till 2nd position are shifted to right by one position. In the fourth iteration, the 4th
element 2 is compared with the 0th element. Since 2 is smaller than 13, the 4th
element is inserted at the 0th place in the array and all the elements from 0th till 3rd
are shifted right by one position. As a result, the array now becomes a sorted array.
First Iteration Second Iteration Third Iteration Fourth Iteration

25 17 31 13 2 25 31 13 17 25 31 13 2 13 17 25 31 2

17 25 31 13 2 13 17 25 31 2 2 13 17 25 31

13 17 25 31 2 12 13 17 25 31

12 13 17 25 31
Steps in the Insertion
Sort

Good and Bad Input Cases: In the best case of an already sorted array, this
implementation of insertion sort takes O(n) time: in each iteration, the first
remaining element of the input is only compared with the last element of the result.
It takes O(n2) time in the average and worst cases, which makes it impractical for
sorting large numbers of elements. However, insertion sort's inner loop is very fast,
which often makes it one of the fastest algorithms for sorting small numbers of
elements, typically less than 10 or so.
Comparisons to Other Sorts: Insertion sort is very similar to bubble sort. In bubble
sort, after k passes through the array, the k largest elements have bubbled to the

34
top. (Or the k smallest elements have bubbled to the bottom, depending on which
way you do it.) In insertion sort, after k passes through the array, you have a run of
k sorted elements at the bottom of the array. Each pass inserts another element into
the sorted run. So with bubble sort, each pass takes less time than the previous one,
but with insertion sort, each pass may take more time than the previous one.
Algorithm: The formal algorithm of insertion sort is given below:
void insertSort(int a[], int length)
{ int i, j, value;
for(i = 1; i < length; i++)
{ value = a[i];
for (j = i - 1; j >= 0 && a[j] > value; j--)
a[j + 1] = a[j];
a[j + 1] = value;
}
}
The following program illustrates the C++ implementation of the insertion sort on
a list of numbers maintained as an array.
//Program that implements insertion sort on a list of numbers maintained as
//an array of numbers
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
const int MAX=50;
class array
{ private:
int arr[MAX];
int count;
public:
array()
{count=0;}
void add(int);
void display(void);
void sort(void);
};
//adds a new element to the array
void array::add(int item)
{ if(count<MAX)
{ arr[count]=item; count++;}

35
else
cout<<"\nArray is full"<<endl;
}
//Display the elements in the list
void array::display(void)
{ cout<<"There are "<<count <<" elements in the list"<<endl;
cout<<"They are :"<<endl<<endl;
for(int i=0;i<count;i++)
cout<<arr[i]<<" ";
}
//Insertion Sort
void array::sort(void)
{ for(int i=1;i<count;i++)
{ int value=arr[i];
for(int j=i-1;((j>=0)&& (arr[j]>value));j--)
arr[j+1]=arr[j];
arr[j+1]=value;
}
return;
}
void main()
{ int element,n,i,c;
array insertion;
while(1)
{ clrscr();
gotoxy(20,10);
cout<<"Perform the Insertion Sort";
gotoxy(20,11);
cout<<"-------------------------" <<endl;
gotoxy(20,12);
cout<<"1. Input data into the list";
gotoxy(20,13);
cout<<"2. Display data in the list";
gotoxy(20,14);
cout<<"3. Sort the list";
gotoxy(20,15);
cout<<"4. Exit from program";
do
{gotoxy(20,17);
cout<<"Select Your Choice(1:4):";

36
cin>>c; gotoxy(43,17); cout<<"";
}
while((c<1)||(c>4));
if(c==4)exit(1); clrscr();
switch(c)
{ case 1:
clrscr();
cout<<"How many elements: ";
cin>>n;
cout<<endl<<endl;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1<<" : ";
cin>>element;
insertion.add(element);
}
break;
case 2:
clrscr();
insertion.display(); break;
case 3:
clrscr();
insertion.sort();
cout<<"List is successfully sorted !" <<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}
The following program illustrates the C++ implementation of the insertion sort on
a list of numbers maintained as a linked list.
//Program that implements insertion sort //on a list of numbers maintained as
//a linked list of numbers
#include <iostream.h>
#include<conio.h>
#include<stdlib.h>
class array
{ private :
struct node

37
{ int data; node *link;}*start;
public :
array();
~array();
void add(int);
void display(void);
void sort(void);
};
// initializes data member
array::array()
{ start= new node;
start->link=NULL; start->data=0;
}
// deallocates memory
array::~array()
{ node *current;
while(start!=NULL)
{ current=start->link;
delete current; start=current;
}
}
// insert element
void array::add(int val)
{ node *current;
start->data++;
current = new node;
current->link = start->link;
current->data=val;
start->link=current;
}
// displays the contents of the list
void array::display()
{ node *current;
cout<<"There are "<<start->data<<" elements in the list" <<endl
<<"They are: "<<endl;
for(current=start->link;current; current=current->link)
cout<<current->data<<" ";
}
//Insertion sort
void array::sort(void)

38
{ node *t1,*t2,*old1,*old2;
old1=start->link;
for(t1=start->link->link; t1!=NULL; t1=t1->link)
{ old2=start;
for(t2=start->link;t2!=t1;t2=t2->link)
{ if(t2->data>t1->data)
{ old1->link=t1->link;
old2->link=t1; t1->link=t2;
break;
}
old2=t2;
}
old1=t1;
}
return;
}
void main()
{ int element,n,i,c;
array Insertion;
while(1)
{ clrscr(); gotoxy(20,10);
cout<<"Perform the Insertion Sort";
gotoxy(20,11);
cout<<"------------------------" <<endl;
gotoxy(20,12);
cout<<"1. Input data into the list";
gotoxy(20,13);
cout<<"2. Display data in the list";
gotoxy(20,14);
cout<<"3. Sort the list";
gotoxy(20,15);
cout<<"4. Exit from program";
do
{gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<"";
}
while((c<1)||(c>4));
if(c==4)exit(1); clrscr();
switch(c)

39
{ case 1:
clrscr();
cout<<"How many elements: ";
cin>>n;
cout<<endl<<endl;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1<<" : ";
cin>>element;
Insertion.add(element);
}
break;
case 2:
clrscr(); Insertion.display();
break;
case 3:
clrscr();
Insertion.sort();
cout<<"List sorted successfully!" <<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}
The following program illustrates the C++ implementation of the insertion sort on
a file of records containing employee details. The file records are temporarily
maintained as an array of records in memory for the purpose of displaying and
sorting the file contents.
//Applying insertion sort to a file of records containing employee details
#include<fstream.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<iomanip.h>
const int MAX=20;
class employee
{ private:
struct empl

40
{ char emplname[20];
int emplcode;
char desig[20];
int salary;
}arr[MAX];
int emplcount;
public:
employee()
{ emplcount=0;}
void add(void);
void display(void);
void search(void);
void sort(void);
};
void employee::add(void)
{ char choice;
fstream file("employee.dat",ios::out);
if(file.fail())
{ cout<<"Error in Opening the file employee.dat";
exit(1);
}
do
{ clrscr(); gotoxy(10,3);
cout<<"Enter the Following Details";
gotoxy(10,4);
cout<<"---------------------------";
gotoxy(10,6);
cout<<"Employee Name : ";
gotoxy(10,7);
cout<<"Employee Code : ";
gotoxy(10,8);
cout<<"Designation : ";
gotoxy(10,9);
cout<<"Salary : ";
cin.ignore(1);
gotoxy(27,6);
cin.getline (arr[emplcount].emplname , 20);
gotoxy(27,7);
cin>>arr[emplcount].emplcode;
gotoxy(27,8);

41
cin.ignore(1);
cin.getline(arr[emplcount].desig,20);
gotoxy(27,9);
cin>>arr[emplcount].salary;
cin.ignore(1);
do
{ gotoxy(20,12);
cout<<"Add More (y/n): ";
cin.get(choice);
if((toupper(choice)!='Y') && (toupper(choice)!='N'))
{ gotoxy(35,12);
cout<<" Invalid Data";
}
}
while((toupper(choice)!='Y')&& (toupper(choice)!='N'));
emplcount++;
}
while((toupper(choice)=='Y'));
for(int i=0;i<emplcount;i++)
file<<arr[i].emplname<<endl <<arr[i].emplcode<<endl <<arr[i].desig
<<endl <<arr[i].salary<<endl;
file.close();
}
void employee::display(void)
{ int i=0;
fstream file("employee.dat",ios::in);
if(file.fail())
{ cout<<"Error in Opening the file employee.dat";
exit(1);
}
clrscr();
while(!file.eof())
{ file.getline(arr[i].emplname,20);
file>>arr[i].emplcode;
file.ignore(1);
file.getline(arr[i].desig,20);
file>>arr[i].salary;
file.ignore(1);
if(file.eof()) break;
i++;

42
}
emplcount=i;
cout<<"Employee Name\t Empl.Code\tDesignation\t Salary"<<endl;
for(i=0;i<70;++i) cout<<'-';
cout<<endl;
for(i=0;i<emplcount;i++)
{ cout.width(20);
cout<<setiosflags(ios::left) <<arr[i].emplname;
cout.width(10);
cout<<arr[i].emplcode;
cout.width(20);
cout<<arr[i].desig;
cout.width(6);
cout<<setiosflags(ios::right) <<arr[i].salary<<endl;
}
for(i=0;i<70;++i) cout<<'-';
file.close();
}
//Sort the array using insertion sort
void employee::sort(void)
{ for(int i=0;i<emplcount;i++)
{ empl value=arr[i];
for(int j=i-1; ((j>=0) && (arr[j].emplcode> value.emplcode)) ; j--)
arr[j+1]=arr[j];
arr[j+1]=value;
}
fstream file("employee.dat",ios::out);
if(file.fail())
{ cout<<"Error in Opening the file employee.dat";
exit(1);
}
for(i=0;i<emplcount;i++)
file<<arr[i].emplname<<endl <<arr[i].emplcode<<endl <<arr[i].desig
<<endl <<arr[i].salary<<endl;
file.close();
return;
}
void main()
{ int c;
employee e;

43
while (1)
{ clrscr(); gotoxy(20,10);
cout<<"Insertion Sort on an Employee Database";
gotoxy(20,11);
cout<<"---------------------------------" <<endl;
gotoxy(20,12);
cout<<"1. Build an Employee File";
gotoxy(20,13);
cout<<"2. List the Contents of the Employee File";
gotoxy(20,14);
cout<<"3. Sort the Employee File";
gotoxy(20,15);
cout<<"4. Exit from Program";
do
{ gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<" ";
}
while((c<1) || (c>4));
if (c==4) exit(1); clrscr();
switch(c)
{ case 1:
e.add(); break;
case 2:
e.display(); break;
case 3:
e.sort();
cout<<"File Sorted Successfully!"<<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}

7.3.2. BUBBLE SORT


Bubble sort, also known as exchange sort, is the oldest and simplest sorting
algorithm in use. Bubble sort works by comparing each item in the list with the
item next to it, and swapping these two items if they are in the wrong order. The
pass through the list is repeated until no swaps are needed, which means the list is

44
sorted. The algorithm gets its name from the way the larger values "bubble" to the
end of the list while smaller values "sink" towards the beginning of the list via the
swaps. Because it only uses comparisons to read elements, it is a comparison sort.
In more detail, the bubble sort algorithm works as follows:
1. Compare adjacent elements. If the first is greater than the second, swap them.
2. Do this for each pair of adjacent elements, starting with the first two and ending
with the last two. At this point the last element should be the greatest.
3. Repeat the steps for all elements except the last one.
4. Keep repeating for one fewer elements each time, until no more pairs to
compare. (Alternatively, keep repeating until no swaps are needed.)
Example: The first iteration of this algorithm begins with comparing 0th element
with the 1st element. If it is found to be greater than the 1st element, then they are
interchanged. Next, the 1st element is compared with the 2nd element, if it is found
to be greater, then they are interchanged. In the same way all the elements
(excluding the last) are compared with their next element and are interchanged, if
required. On completing the first iteration, the largest element gets placed at the
last position. Similarly, in the second iteration, comparisons are made till the last
but one element and this time the second largest element gets placed at the second
last position in the list. As a result, after all iterations, the list becomes a sorted list.
This procedure is illustrated below for an array that contains 5 elements. In the first
iteration, 0th element 25 is compared with the first element 17 and since 25 is
greater than 17, they are interchanged. Now, the 1st element 25 is compared with
2nd element 31. But 25 being less than 31, they are not interchanged. This process
is repeated until (n-2)nd element is compared with the (n-1)th element. During the
comparison, if (n-2)nd element is found to be greater than (n-1)th element, then they
are interchanged. At the end of the first iteration, the (n-1)th element holds the
largest number. Now the second iteration starts with the 0th element 17. The above
process of comparison and interchanging is repeated but this time the last
comparison is made between (n-3)rd and (n-2)nd elements. If there are n elements,
then (n-1) iterations need to be performed.
First Iteration Second Iteration Third Iteration Fourth Iteration

25 17 31 13 2 17 25 13 2 31 17 13 2 25 31 13 17 2 25 31

17 25 31 13 2 17 25 13 2 31 13 17 2 25 31

17 25 31 13 2 17 13 25 2 31

17 25 13 31 2

17 25 13 2 31 17 13 2
4525 31 13 17 2 25 31 13 17 2 25 31

Steps in the Bubble Sort


Algorithm: The formal algorithm of bubble sort is given below
void BubbleSort(int arr[], int n)
{ int i, j, temp;
for (i = 0; i<(n - 1); i++)
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; }
}
Performance: The bubble sort is generally considered to be the most inefficient
sorting algorithm in common usage. Under best-case conditions (the list is already
sorted), the bubble sort can approach a constant O(n) level of complexity. In
general-case, bubble sort needs O(n2) comparisons to sort n items and can sort in-
place. Although the algorithm is one of the simplest sorting algorithms to
understand and implement, it is too inefficient for use on lists having more than a
few elements. Even among simple O(n2) sorting algorithms, algorithms like
insertion, selection and shell sorts are considerably more efficient.
Bubble sort is asymptotically equivalent in running time to insertion sort in the
worst case, but the two algorithms differ greatly in the number of swaps necessary.
Insertion sort needs only O(n) operations if the list is already sorted, whereas naïve
implementations of bubble sort (like the pseudocode above) require O(n2)
operations. (This can be reduced to O(n) if code is added to stop the outer loop
when the inner loop performs no swaps.)
The following program illustrates the C++ implementation of the bubble sort on a
list of numbers maintained as an array.
//Program that implements bubble sort
//on a list of numbers maintained as
//an array
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
const int MAX=50;
class array
{ private:
int arr[MAX];
int count;
public:
array()
{count=0;}

46
void add(int);
void display(void);
void sort(void);
};
//adds a new element to the array
void array::add(int item)
{ if(count<MAX)
{ arr[count]=item;
count++;
}
else
cout<<"\nArray is full"<<endl;
}
//Display the elements in the list
void array::display(void)
{ cout<<"There are "<<count<<" elements in the list"<<endl;
cout<<"They are :"<<endl<<endl;
for(int i=0;i<count;i++)
cout<<arr[i]<<" ";
}
//Bubble Sort
void array::sort(void)
{ for(int i=0;i<count-1;i++)
{ int flag = 1;
for(int j=0;j<(count-i-1);j++)
if(arr[j]>arr[j+1])
{ int t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
flag=0;
}
if(flag) break;
}
return;
}
void main()
{ int element,n,i,c;
array Bubble;
while(1)
{ clrscr();

47
gotoxy(20,10);
cout<<"Perform the Bubble Sort";
gotoxy(20,11);
cout<<"-------------------------" <<endl;
gotoxy(20,12);
cout<<"1. Input data into the list";
gotoxy(20,13);
cout<<"2. Display data in the list";
gotoxy(20,14);
cout<<"3. Sort the list";
gotoxy(20,15);
cout<<"4. Exit from program";
do
{gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<"";
}
while((c<1)||(c>4));
if(c==4)exit(1); clrscr();
switch(c)
{ case 1:
clrscr();
cout<<"How many elements: ";
cin>>n;
cout<<endl<<endl;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1<<" : ";
cin>>element;
Bubble.add(element);
}
break;
case 2:
clrscr(); Bubble.display(); break;
case 3:
clrscr();
Bubble.sort();
cout<<"List is successfully sorted !" <<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";

48
getch();
}
}
The following program illustrates the C++ implementation of the bubble sort on a
list of numbers maintained as a linked list.
//Program that implements bubble sort on a list of numbers maintained
//as a linked list
#include <iostream.h>
#include<conio.h>
#include<stdlib.h>
class array
{ private :
struct node
{ int data;
node *link;
}*start;
public :
array();
~array();
void add(int);
void display(void);
void sort(void);
};
// initializes data member
array::array()
{ start= new node;
start->link=NULL;
start->data=0;
}
// deallocates memory
array::~array()
{ node *current;
while(start!=NULL)
{ current=start->link;
delete current;
start=current;
}
}
// insert element

49
void array::add(int val)
{ node *current;
start->data++;
current = new node;
current->link = start->link;
current->data=val; start->link=current;
}
// displays the contents of the list
void array::display()
{ node *current;
cout<<"There are "<<start->data << " elements in the list" <<endl <<"They
are: "<<endl;
for(current=start->link; current;current=current->link)
cout<<current->data<<" ";
}
//Bubble sort
void array::sort(void)
{ node *t1,*t2,*old, *temp;
for(t1=start->link;t1->link!=NULL; t1=t1->link)
{ old=start;
int flag=1;
for(t2=start->link;t2->link!=NULL; t2=t2->link)
{ if(t2->data>t2->link->data)
{ temp=t2->link;
t2->link=t2->link->link;
old->link=temp;
temp->link=t2;
flag=0;
}
old=t2;
}
if(flag) break;
}
return;
}
void main()
{ int element,n,i,c;
array Bubble;
while(1)
{ clrscr(); gotoxy(20,10);

50
cout<<"Perform the Bubble Sort";
gotoxy(20,11);
cout<<"------------------------" <<endl;
gotoxy(20,12);
cout<<"1. Input data into the list";
gotoxy(20,13);
cout<<"2. Display data in the list";
gotoxy(20,14);
cout<<"3. Sort the list";
gotoxy(20,15);
cout<<"4. Exit from program";
do
{gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<"";
}
while((c<1)||(c>4));
if(c==4)exit(1); clrscr();
switch(c)
{ case 1:
clrscr();
cout<<"How many elements: ";
cin>>n;
cout<<endl<<endl;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1<<" : ";
cin>>element;
Bubble.add(element);
}
break;
case 2:
clrscr(); Bubble.display(); break;
case 3:
clrscr();
Bubble.sort();
cout<<"List sorted successfully...!"<<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();

51
}
}
The following program illustrates the C++ implementation of the bubble sort on a
file of records containing employee details. The file records are temporarily
maintained as an array of records in memory for the purpose of displaying and
sorting the file contents.
//Applying Bubble sort to a file
#include<fstream.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<iomanip.h>
const int MAX=20;
class employee
{ private:
struct empl
{ char emplname[20];
int emplcode;
char desig[20];
int salary;
}arr[MAX];
int emplcount;
public:
employee()
{ emplcount=0;}
void add(void);
void display(void);
void search(void);
void sort(void);
};
void employee::add(void)
{ char choice;
fstream file("employee.dat",ios::out);
if(file.fail())
{ cout<<"Error in Opening the file employee.dat";
exit(1);
}
do

52
{ clrscr(); gotoxy(10,3);
cout<<"Enter the Following Details";
gotoxy(10,4);
cout<<"---------------------------";
gotoxy(10,6);
cout<<"Employee Name : ";
gotoxy(10,7);
cout<<"Employee Code : ";
gotoxy(10,8);
cout<<"Designation : ";
gotoxy(10,9);
cout<<"Salary : ";
cin.ignore(1); gotoxy(27,6);
cin.getline (arr[emplcount].emplname, 20);
gotoxy(27,7);
cin>>arr[emplcount].emplcode;
gotoxy(27,8); cin.ignore(1);
cin.getline(arr[emplcount].desig,20);
gotoxy(27,9);
cin>>arr[emplcount].salary;
cin.ignore(1);
do
{ gotoxy(20,12);
cout<<"Add More (y/n): ";
cin.get(choice);
if((toupper(choice)!='Y')&& (toupper(choice)!='N'))
{ gotoxy(35,12);
cout<<" Invalid Data";
}
}
while((toupper(choice)!='Y')&& (toupper(choice)!='N'));
emplcount++;
}
while((toupper(choice)=='Y'));
for(int i=0;i<emplcount;i++)
file<<arr[i].emplname<<endl <<arr[i].emplcode<<endl <<arr[i].desig<<endl
<<arr[i].salary<<endl;
file.close();
}
void employee::display(void)

53
{ int i=0;
fstream file("employee.dat",ios::in);
if(file.fail())
{ cout<<"Error in Opening the file employee.dat";
exit(1);
}
clrscr();
while(!file.eof())
{ file.getline(arr[i].emplname,20);
file>>arr[i].emplcode;
file.ignore(1);
file.getline(arr[i].desig,20);
file>>arr[i].salary;
file.ignore(1);
if(file.eof()) break;
i++;
}
emplcount=i;
cout<<"Employee Name\t Empl.Code\tDesignation\t Salary"<<endl;
for(i=0;i<70;++i) cout<<'-';
cout<<endl;
for(i=0;i<emplcount;i++)
{ cout.width(20);
cout<<setiosflags(ios::left) <<arr[i].emplname;
cout.width(10);
cout<<arr[i].emplcode;
cout.width(20);
cout<<arr[i].desig;
cout.width(6);
cout<<setiosflags(ios::right) <<arr[i].salary<<endl;
}
for(i=0;i<70;++i)cout<<'-';
file.close();
}
//Sort the array using insertion sort
void employee::sort(void)
{ for(int i=0;i<emplcount-1;i++)
for(int j=0;j<(emplcount-i-1);j++)
if(arr[j].emplcode> arr[j+1].emplcode)
{ empl t=arr[j];

54
arr[j]=arr[j+1]; arr[j+1]=t;
}
fstream file("employee.dat",ios::out);
if(file.fail())
{ cout<<"Error in Opening the file employee.dat";
exit(1);
}
for(i=0;i<emplcount;i++)
file<<arr[i].emplname<<endl <<arr[i].emplcode<<endl <<arr[i].desig<<endl
<<arr[i].salary <<endl;
file.close(); return;
}
void main()
{ int c;
employee e;
while (1)
{ clrscr(); gotoxy(20,10);
cout<<"Bubble Sort on an Employee Database";
gotoxy(20,11);
cout<<"----------------------------------" <<endl;
gotoxy(20,12);
cout<<"1. Build an Employee File";
gotoxy(20,13);
cout<<"2. List the Contents of the Employee File";
gotoxy(20,14);
cout<<"3. Sort the Employee File";
gotoxy(20,15);
cout<<"4. Exit from Program";
do
{ gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<" ";
}
while((c<1) || (c>4));
if (c==4) exit(1); clrscr();
switch(c)
{ case 1:
e.add(); break;
case 2:
e.display(); break;

55
case 3:
e.sort();
cout<<"File Sorted Successfully!"<<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}

7.3.3. SELECTION SORT


A selection sort is one of the simplest sorts to implement. It is basically a
comparison sort. The selection sort works by selecting the smallest unsorted item
remaining in the list, and then swapping it with the item in the next position to be
filled. The idea of selection sort is rather simple: we repeatedly find the next
smallest (or largest) element in the array and move it to its final position in the
sorted array. Assume that we wish to sort the array in increasing order, i.e. the
smallest element at the beginning of the array and the largest element at the end.
We begin by selecting the smallest element and moving it to the smallest index
position. We can do this by swapping the element at the smallest index and the
smallest element. We then reduce the effective size of the array by one element and
repeat the process on the smaller (sub)array. The process stops when the effective
size of the array becomes 1 (an array of 1 element is already sorted).
Algorithm: The formal algorithm of selection sort is given below
void SelectionSort(int arr[], int n)
{ int i, j, min, temp;
for (i = 0; i < n-1; i++)
{ min = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min]) min = j;
{temp = arr[i]; arr[i] = arr[min]; arr[min] = temp;}
}
}
Example: The first iteration of the selection sort begins by comparing the 0th
element with all other elements. If the 0th element is found to be greater than the
compared element, then they are interchanged. So after the first iteration, the
smallest element is placed at 0th position. The same procedure is repeated for the

56
1st element and so on. This procedure is illustrated below for an array that contains
5 elements:
First Iteration Second Iteration Third Iteration Fourth Iteration

25 17 31 13 2 2 25 31 17 13 2 13 31 25 17 2 13 17 31 25

17 25 31 13 2 2 25 31 17 13 2 13 25 31 17 2 13 17 31 25

17 25 31 13 2 2 17 31 25 13 2 13 17 31 25

13 25 31 17 2 2 13 31 25 17

2 25 31 17 13

Steps in the Selection Sort

Performance: This algorithm, iterating through a list of n unsorted items, has a


worst-case, average-case, and best-case run-time of O(n2), assuming that
comparisons can be done in constant time. Among simple O(n2) algorithms, it is
generally outperformed by insertion sort, but still tends to outperform contenders
such as bubble sort. Selection sort is simple and easy to implement. But it is
inefficient for large lists, so similar to the more efficient insertion sort should be
used in its place. The selection sort is the unwanted stepchild of the O(n2) sorts. It
yields a 60% performance improvement over the bubble sort, but the insertion sort
is over twice as fast as the bubble sort and is just as easy to implement as the
selection sort. In short, there really isn't any reason to use the selection sort - use
the insertion sort instead.
The following program illustrates the C++ implementation of the selection sort on
a list of numbers maintained as an array.
//Program that implements Selection sort on a list of numbers maintained as
//an array
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
const int MAX=50;
class array
{ private:
int arr[MAX]; int count;
public:
array()

57
{count=0;}
void add(int);
void display(void);
void sort(void);
};
//adds a new element to the array
void array::add(int item)
{ if(count<MAX)
{ arr[count]=item; count++;}
else
cout<<"\nArray is full"<<endl;
}
//Display the elements in the list
void array::display(void)
{ cout<<"There are "<<count<<" elements in the list"<<endl;
cout<<"They are :"<<endl<<endl;
for(int i=0;i<count;i++)
cout<<arr[i]<<" ";
}
//Sort the array using selection sort
void array::sort(void)
{ int i,j, min,temp;
for(i=0;i<count-1;i++)
{ min=i;
for(j=i+1;j<count;j++)
if(arr[j]<arr[min]) min=j;
{ temp=arr[i]; arr[i]=arr[min];
arr[min]=temp;
}
}
return;
}
void main()
{ int element,n,i,c;
array Selection;
while(1)
{ clrscr(); gotoxy(20,10);
cout<<"Perform the Selection Sort";
gotoxy(20,11);
cout<<"-----------------------" <<endl;

58
gotoxy(20,12);
cout<<"1. Input data into the list";
gotoxy(20,13);
cout<<"2. Display data in the list";
gotoxy(20,14);
cout<<"3. Sort the list";
gotoxy(20,15);
cout<<"4. Exit from program";
do
{gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<"";
}
while((c<1)||(c>4));
if(c==4)exit(1); clrscr();
switch(c)
{ case 1:
clrscr();
cout<<"How many elements: ";
cin>>n; cout<<endl<<endl;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1<<" : ";
cin>>element;
Selection.add(element);
}
break;
case 2:
clrscr();
Selection.display(); break;
case 3:
clrscr(); Selection.sort();
cout<<"List is successfully sorted !" <<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}

59
7.3.4. QUICK SORT
As its name implies, quick sort is the fastest known sorting algorithms. Quick sort
is a comparison sort and, in efficient implementations, is not a stable sort. It is an
in-place, divide-and-conquer, massively recursive sort. It is essentially a faster in-
place version of the merge sort. Let S be an array, and n the number of elements in
the array to be sorted. Choose an element v (known as pivot element) from a
specific position within the array (for example, v can be chosen as the first element
so that v=S[0]). Suppose that the elements of S are partitioned so that v is placed
into position j and the following conditions hold:
1. Each of the elements in positions 0 through j-1 is less than or equal to v.
2. Each of the elements in positions j+1 through n-1 is greater than or equal to v.
Notice that if these two conditions hold for a particular v and j, v is the jth smallest
element of S, so that v remains in position j when the array is completely sorted.
The basic recursive algorithm for quick sort consists of the following four steps:
1. If the number of elements in the array to be sorted (S) is 0 or 1, return
immediately.
2. Pick an element (v) in the array to serve as a "pivot" point. (Usually the left-
most element in the array is used.)
3. Split the array into two parts - one with elements larger than the pivot and the
other with elements smaller than the pivot.
4. Recursively repeat the algorithm for both halves of the original array.
Suppose that an array arr consists of 10 elements. The quick sort algorithm works
as follows:
• In the first iteration, we will place the 0th element 11 at its final position and
divide the array. Here, 11 is the pivot element. To divide the array, two index
variables p and q, are taken. The indexes are initialized such a way that, p refers
to the 1st element 2 and q refers to the (n-1)th element 3.
• The job of the index variable p is to search an element that is greater than the
value at 0th location. So p is incremented by one till the value stored at p is
greater than 0th element. In our case it is incremented till 13, as 13 is greater
than 11.
• Similarly, q needs to search an element that is smaller than the 0th element. So q
is decremented by 1 till the value stored at q is smaller than the value at 0th
location. In our case q is not decremented because 3 is less than 11.

60
11 2 9 13 57 25 17 1 90 3

11 2 9 13 57 25 17 1 90 3

11 2 9 13 57 25 17 1 90 3

11 2 9 3 57 25 17 1 90 13

11 2 9 3 57 25 17 1 90 13

11 2 9 3 1 25 17 57 90 13

1 2 9 3 11 25 17 57 90 13

Steps in Quick Sort


• When these elements are found, they are interchanged. Again from the current
positions p and q are incremented and decremented, respectively and exchanges
are made appropriately if desired.
• The process ends whenever the index pointers meet or crossover. In our case,
they are crossed at the values 1 and 25 for the indexes q and p, respectively.
Finally, the 0th element 11 is interchanged with the value at index q, i.e., 1. The
position q is now the final position of the pivot element 11.
• As a result, the whole array is divided into two parts. Where all the elements
before 11 are less than 11 and all the elements after 11 are greater than 11.
• Now the same procedure is applied for the two sub arrays. As a result, at the
end when all the sub-arrays are loft with one element, the original array
becomes sorted.
Here, it is not necessary that the pivot element whose position is to be finalized in
the first iteration must be 0th element. It can be any other element as well.
The efficiency of the algorithm is primarily impacted by which element is chosen
as the pivot point. The worst-case efficiency of the quick sort, O(n2), occurs when
the list is sorted and the left-most element is chosen. Randomly choosing a pivot
point rather than using the left-most element is recommended if the data to be
sorted is not random. As long as the pivot point is chosen randomly, the quick sort
has an algorithmic complexity of O(n log n).
The quick sort is by far the fastest of the common sorting algorithms. But its
algorithm is very complex and is massively recursive. In most cases the quick sort
is the best choice if speed is important (and it almost always is). Use it for

61
repetitive sorting, sorting of medium to large lists, and as a default choice when
you are not really sure which sorting algorithm to use.
The following program illustrates the recursive C++ implementation of the quick
sort on a list of numbers maintained as an array.
//Program that implements insertion sort
//on a list of numbers
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
const int MAX=50;
class array
{ private:
int arr[MAX]; int count;
public:
array()
{count=0;}
int getcount()
{return count;}
void add(int);
void display(void);
int split(int *, int, int);
void q_sort(int,int);
};
//adds a new element to the array
void array::add(int item)
{ if(count<MAX)
{ arr[count]=item; count++; }
else
cout<<"\nArray is full"<<endl;
}
//Display the elements in the list
void array::display(void)
{ cout<<"There are "<<count<< " elements in the list"<<endl;
cout<<"They are :"<<endl<<endl;
for(int i=0;i<count;i++)
cout<<arr[i]<<" ";
}
void array::q_sort(int lower, int upper)
{ if(upper>lower)

62
{ int v = split(arr, lower, upper);
q_sort(lower, v-1);
q_sort(v+1, upper);
}
}
//Sort the array using quick sort
int array::split(int *arr, int lower,int upper)
{ int v,p,q,t;
p=lower+1; q=upper; v=arr[lower];
while(q>=p)
{ while(arr[p]<v) p++;
while(arr[q]>v) q--;
if(q>p)
{ t=arr[p];arr[p]=arr[q];arr[q]=t;}
}
t=arr[lower];arr[lower]=arr[q];arr[q]=t;
return q;
}
void main()
{ int element,n,i,c;
array quick;
while(1)
{ clrscr(); gotoxy(20,10);
cout<<"Perform the Quick Sort";
gotoxy(20,11);
cout<<"------------------------" <<endl;
gotoxy(20,12);
cout<<"1. Input data into the list";
gotoxy(20,13);
cout<<"2. Display data in the list";
gotoxy(20,14);
cout<<"3. Sort the list";
gotoxy(20,15);
cout<<"4. Exit from program";
do
{ gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<"";
}
while((c<1)||(c>4));

63
if(c==4)exit(1); clrscr();
switch(c)
{ case 1:
clrscr();
cout<<"How many elements: ";
cin>>n;
cout<<endl<<endl;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1 <<" : ";
cin>>element;
quick.add(element);
}
break;
case 2:
clrscr(); quick.display();break;
case 3:
clrscr();
quick.q_sort(0, quick.getcount()-1);
cout<<"List is successfully sorted !"<<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}

7.3.5. HEAP SORT


One simple way to sort a list of objects is to use a heap data structure. A heap is a
specialized complete binary tree-based data structure. Suppose H is complete
binary tree with n elements. Then H is called maxheap or descending heap, if each
node N of H has the following property: The value at N is greater than or equal to
the value at each of the children of N. (A minheap is defined analogously: The
value at N is less than or equal to the value at any of the children of N). Due to this
fact, heaps are used to implement priority queues.
Heaps are used in the sorting algorithm called Heap sort. Heap sort is one of the
best general-purpose sort algorithms, a comparison sort and part of the selection
sort family. Although somewhat slower in practice on most machines than a good
implementation of quick sort, it has the advantages of worst-case O(n log n)
runtime and being an in-place algorithm. Heap sort is not a stable sort. The heap

64
sort is the slowest of the O(n log n) sorting algorithms, but unlike the merge and
quick sorts it doesn't require massive recursion or multiple arrays to work. This
makes it the most attractive option for very large data sets of millions of items.
The heap sort works as it name suggests - it begins by building a heap out of the
data set, and then removing the largest item and placing it at the end of the sorted
array. After removing the largest item, it reconstructs the heap and removes the
largest remaining item and places it in the next open position from the end of the
sorted array. This is repeated until there are no items left in the heap and the sorted
array is full.
A common approach to implement a heap is to store the heap in an array. The 0th
element will be the root and left and right child of any node arr[i] would be at
arr[2i+1] and arr[2i+2]. Note that with an implementation starting at 0 for the root,
the parent of arr[i] is arr[floor(i-1)/2). This approach is particularly useful in the
heapsort algorithm, where it allows the space in the input array to be reused to
store the heap.
The implementation of heapsort requires two arrays - one to hold the heap and the
other to hold the sorted elements. In doing so, the only extra space required is that
needed to store the heap. To do an in-place sort and save the space the second array
would require, we use an algorithm which uses the same array to store both the
heap and the sorted array. The adjustment of the nodes starts from the level one
less than the maximum level of the tree (as the leaf nodes are always heap). Each
subtree of a particular level is made a heap. Then all the subtrees at the level two
less than the maximum level of tree are made heaps. This procedure is repeated till
the root node. As a result the final tree becomes a heap.
As an example, consider an array that contains 15 elements given below:
7 10 25 17 23 27 16 19 37 42 4 33 1 5 11
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
The tree that can be constructed from the array is shown below:
7
10 25
17 23 27 16

19 37 42 4 33 1 5 11

To make it a heap, initially the elements that are present at level one less than the
maximum level of the tree are taken into consideration. In the case of above
example, these are 17, 23, 27 and 16. They are converted into heap by comparing

65
and interchanging, if necessary, these nodes with their respective parents. The
resulting tree looks like the one shown below:
7
10 25
37 42 33 16

19 17 23 4 27 1 5 11

Now the elements that are present at a level two less than the maximum level of
the tree are considered. In the case of above example, these are 10 and 25. These
are also made the heap by the same procedure. The resulting tree looks like the one
shown below:
7

42 33
37 23 27 16

19 17 10 4 25 1 5 11

Similarly, each time one level is decremented and all the subtrees at that level are
converted to heaps. As a result, finally the entire gets converted into heap, as
shown below:
42

37 33
19 23 27 16

7 17 10 4 25 1 5 11

The array element arr[i] is placed into its proper place by traversing the path from
position i in the array to position 0 (root), seeking the first element greater than or
equal to the element arr[i]. When that element is found, the element arr[i] is
inserted immediately preceding it in the path (that is arr[i] is inserted as its son).
As each element less than arr[i] is passed during the traversal, it is shifted down
one level in the tree to make room for the element to be inserted.
The algorithm for creating a binary heap from an array is given below:
void CreateHeap(int arr[], int size)
{ int i,f,s;
for(i=1;i<size;i++)
{ int element=arr[i];

66
son=i; father=(son-1)/2;
while(son>0 && arr[father]<element)
{ arr[son]=arr[father]; son=father; father=(son-1)/2; }
arr[son]=element;
}
Whenever an item is removed from the heap, it frees up a space at the end of the
array that the removed item can be placed in. Heap sort makes use of two standard
heap operations: insertion and root deletion. Each time we delete (extract) the
maximum, we place it in the last location of the array not yet occupied, and use the
remaining prefix of the array as a heap holding the remaining unsorted element.
To implement the delete operation, we note that the maximum element is always at
the root of a k-element heap. When that element is deleted, the remaining k-1
elements in position 1 through k-1 must be distributed into positions 0 through k-2
so that the resulting array segment from arr[0] through arr[k-2] remains a heap.
When the root p is deleted, the larger of the sons arr[2p+1] or arr[2p +2] must
move up to take its place as the new largest element. Then the subtree rooted at the
position of the larger element moved up must be readjusted in turn.
void delete( int arr[], int size)
{ for(i=size-1;i>0;i--)
{ //delete arr[i]
int value=arr[i];
arr[i]=arr[0];
f=0;
//determining large son
if(i==1) s=-1;
else
s=1;
if(i>2 && (arr[2]>arr[1])) s=2;
while(s>=0 && value<(arr[s]))
{ arr[f]=arr[s];
f=s; s=2*f+1;
if(s+1<=i-1 && arr[s]<(arr[s+1])) s=s+1;
if(s>i-1) s=-1;
}
arr[f]=value;
}

As an example, consider the sorting of the following heap:

67
42

37 33
19 23 27 16

7 17 10 4 25 1 5 11

4237 33 19 23 27 16 7 17 10 4 25 1 5 11
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Now the root element is 42 is moved to the last location by exchanging it with 11.
Finally, 42 is eliminated from the heap by reducing the maximum index of the
array by 1. The balance elements are then rearranged into heap. The heap and array
are shown below:
37

23 33
19 11 27 16

7 17 10 4 25 1 5

3723 33 19 11 27 16 7 17 10 4 25 1 5 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Similarly, one by one the root element of the heap is eliminated, as illustrated
below:
33

23 27
19 11 25 16

7 17 10 4 5 1

3323 27 19 11 25 16 7 17 10 4 5 1 37 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

27

23 25
19 11 5 16

7 17 10 4 1

68
2723 25 19 11 5 16 7 17 10 4 1 33 33 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

25

23 16
19 11 5 1

7 17 10 4

2523 16 19 11 5 1 7 17 10 4 27 33 33 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
23

19 16
17 11 5 1

7 4 10

2319 16 17 11 5 1 7 4 10 25 27 33 33 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

19

17 16
10 11 5 1

7 4

1917 16 10 11 5 1 7 4 23 25 27 33 33 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

17

11 16
10 4 5 1

69
1711 16 10 4 5 1 7 19 23 25 27 33 33 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
16

11 7

10 4 5 1

1611 7 10 4 5 1 17 19 23 25 27 33 33 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
11
10 7
1 4 5

1110 7 1 4 5 16 17 19 23 25 27 33 33 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
10
5 7
1 4
105 7 1 4 11 16 17 19 23 25 27 33 33 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

5 4

7 5 4 1 10 11 16 17 19 23 25 27 33 33 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
5

1 4

5 1 4 7 10 11 16 17 19 23 25 27 33 33 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
4

1
70
4 1 5 7 10 11 16 17 19 23 25 27 33 33 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
1

1 4 5 7 10 11 16 17 19 23 25 27 33 33 42
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

The following program illustrates the C++ implementation of the heap sort on a list
of numbers maintained as an array. This implementation combines the process of
creating heap from the array and deleting the root node until the tree is empty.
//Program that implements Heap sort on a list of numbers
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
const int MAX=50;
class array
{ private:
int arr[MAX];
int size;
public:
array()
{size=0;}
void add(int);
void display(void);
void sort(void);
};
//adds a new element to the array
void array::add(int item)
{ if(size<MAX)
{ arr[size]=item;
size++;
}
else
cout<<"\nArray is full"<<endl;
}
//Display the elements in the list
void array::display(void)

71
{ cout<<"There are "<<size<<" elements in the list"<<endl;
cout<<"They are :"<<endl<<endl;
for(int i=0;i<size;i++)
cout<<arr[i]<<" ";
}
//an array implementation of heap sort
void array::sort(void)
{ int i,f,s;
for(i=0;i<size;i++)
{ int e=arr[i];
s=i;
f=(s-1)/2;
while(s>0 && arr[f]<e)
{ arr[s]=arr[f];
s=f;
f=(s-1)/2;
}
arr[s]=e;
}
for(i=size-1;i>0;i--)
{ int value=arr[i];
arr[i]=arr[0];
f=0;
if(i==1)
s=-1;
else
s=1;
if(i>2 && (arr[2]>arr[1]))
s=2;
while(s>=0 && value<(arr[s]))
{ arr[f]=arr[s];
f=s;
s=2*f+1;
if(s+1<=i-1 && arr[s]<(arr[s+1]))
s=s+1;
if(s>i-1)
s=-1;
}
arr[f]=value;
}

72
}
void main()
{ int element,n,i,c;
array Heap;
while(1)
{ clrscr();
gotoxy(20,10);
cout<<"Perform the Heap Sort";
gotoxy(20,11);
cout<<"------------------------" <<endl;
gotoxy(20,12);
cout<<"1. Input data into the list";
gotoxy(20,13);
cout<<"2. Display data in the list";
gotoxy(20,14);
cout<<"3. Sort the list";
gotoxy(20,15);
cout<<"4. Exit from program";
do
{gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<"";
}
while((c<1)||(c>4));
if(c==4)exit(1);
clrscr();
switch(c)
{ case 1:
clrscr();
cout<<"How many elements: ";
cin>>n;
cout<<endl<<endl;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1<<" : ";
cin>>element;
Heap.add(element);
}
break;
case 2:
clrscr(); Heap.display(); break;

73
case 3:
clrscr();
Heap.sort();
cout<<"List is successfully sorted !" <<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";
getch();
}
}

7.3.6. MERGE SORT


Merge sort is a sorting algorithm for rearranging lists (or any other data structure
that can only be accessed sequentially, e.g. file streams) into a specified order.
Merge sort is basically a divide and conquer comparison type sort. The algorithm
was invented by John von Neumann in 1945. This algorithm is marginally faster
than the heap sort for larger sets. But it has at least twice the memory requirements
of the other sorts.
The merge sort splits the list to be sorted into two equal halves, and places them in
separate arrays. Each array is recursively sorted, and then merged back together to
form the final sorted list. Like most recursive sorts, the merge sort has an
algorithmic complexity of O(n log n). The Merge-sort algorithm can be described
in general terms as consisting of the following three steps:
1. Divide Step: If given array A has zero or one element, return A; it is already
sorted. Otherwise, divide A into two arrays, A1 and A2, each containing about
half of the elements of A.
2. Recursion Step: Recursively sort array A1 and A2.
3. Conquer Step: Combine the elements back in A by merging the sorted arrays
A1 and A2 into a sorted sequence.
We can visualize Merge-sort by means of binary tree where each node of the tree
represents a recursive call and each external node represents individual elements of
given array A. Such a tree is called Merge-sort tree. The heart of the Merge-sort
algorithm is conquer step, which merge two sorted sequences into a single sorted
sequence
The following program illustrates the recursive implementation of the merge sort.

74
//Program that implements Merge sort
//on a list of numbers
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
const int MAX=50;
class array
{ private:
int arr[MAX];
int size;
public:
array()
{size=0;}
void add(int);
void display(void);
void sort(void);
};
//adds a new element to the array
void array::add(int item)
{ if(size<MAX)
{ arr[size]=item; size++;}
else
cout<<"\nArray is full"<<endl;
}
//Display the elements in the list
void array::display(void)
{ cout<<"There are "<<size <<" elements in the list"<<endl;
cout<<"They are :"<<endl<<endl;
for(int i=0;i<size;i++)
cout<<arr[i]<<" ";
}
void array::sort(void)
{ int temp[MAX];
void m_sort(int[],int[],int,int);
m_sort(arr,temp,0,size-1);
}
void m_sort(int numbers[],int temp[],int left,int right)
{ void merge(int[],int[],int,int,int);
int mid;
if(right>left)

75
{ mid=(right+left)/2;
m_sort(numbers,temp,left,mid);
m_sort(numbers,temp, mid+1,right);
merge(numbers,temp, left,mid+1,right);
}
}
void merge(int numbers[],int temp[],int left,int mid,int right)
{ int i,left_end,num_elements,tmp_pos;
left_end=mid-1;
tmp_pos=left;
num_elements=right-left+1;
while((left<=left_end)&& (mid<=right))
{ if(numbers[left]<=numbers[mid])
{ temp[tmp_pos]=numbers[left];
tmp_pos=tmp_pos+1;
left=left+1;
}
else
{ temp[tmp_pos]=numbers[mid];
tmp_pos=tmp_pos+1;
mid=mid+1;
}
}
while(left<=left_end)
{ temp[tmp_pos]=numbers[left];
left=left+1; tmp_pos=tmp_pos+1;
}
while(mid<=right)
{ temp[tmp_pos]=numbers[mid];
mid=mid+1; tmp_pos=tmp_pos+1;
}
for(i=0;i<=num_elements;i++)
{ numbers[right]=temp[right];
right=right-1;
}
}
void main()
{ int element,n,i,c;
array Heap;
while(1)

76
{ clrscr(); gotoxy(20,10);
cout<<"Perform the Heap Sort";
gotoxy(20,11);
cout<<"------------------------"<<endl;
gotoxy(20,12);
cout<<"1. Input data into the list";
gotoxy(20,13);
cout<<"2. Display data in the list";
gotoxy(20,14);
cout<<"3. Sort the list";
gotoxy(20,15);
cout<<"4. Exit from program";
do
{gotoxy(20,17);
cout<<"Select Your Choice(1:4):";
cin>>c; gotoxy(43,17); cout<<"";
}
while((c<1)||(c>4));
if(c==4)exit(1);
clrscr();
switch(c)
{ case 1:
clrscr();
cout<<"How many elements: ";
cin>>n; cout<<endl<<endl;
for(i=0;i<n;i++)
{ cout<<"Enter a number " <<i+1<<" : ";
cin>>element;
Heap.add(element);
}
break;
case 2:
clrscr(); Heap.display(); break;
case 3:
clrscr();
Heap.sort();
cout<<"List is successfully sorted !" <<endl;
break;
}
cout<<endl<<"Press Any Key to Continue...";

77
getch();
}
}

7.3.7. COMPARISON OF SORTING ALGORITHMS


The following table provides a comparison of the complexity of the various sorting
algorithms under best, average and worst cases.
Name Best Average Worst Stable Method
Bubble sort O(n2) O(n2) O(n2) Yes Exchanging
Selection sort O(n2) O(n2) O(n2) No Selection
Insertion sort O(n) O(n2) O(n2) Yes Insertion
Merge sort O(n log n) O(n log n) O(nlogn) Yes Merging
Heap sort O(n log n) O(n log n) O(n log n) No Selection
Quick sort O(n log n) O(n log n) O(n2) No Partitioning

78

S-ar putea să vă placă și