DSU - CH-2 - Searching and Sorting
DSU - CH-2 - Searching and Sorting
DSU - CH-2 - Searching and Sorting
Unit – 2
Searching and Sorting [12]
Course Outcome: Perform basic operation on array.
Syllabus:
1. Searching an item in a dataset using following methods:
i. Linear Search
ii. Binary Search
2. Sorting of data set in an order using following methods:
i. Bubble Sort
ii. Selection Sort
iii. Insertion Sort
iv. Quick Sort
v. Radix Sort
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
SEARCHING
We often spend time in searching for the desired item. If the data is kept properly in sorted order
then searching becomes very easy and efficient.
Searching is an operation which finds the place of a given element in the list. The search is said to
be successful or unsuccessful depending upon whether the element is found or not found.
This is the simplest method of searching. In this method, the element to be found is
searched sequentially in the list. This method can be used on sorted or unsorted list.
Linear search is also called as sequential search. Linear search is the easiest search
techniquein which each element is scanned in a sequential manner to locate the desire
element.
Linear search is a method for finding a particular value in a list. In this searching
technique you needto check every element one by one until desired element fou
___________________________________________________________________________
Key Element = 91
_____________________________________________________________________________________________
Step 6: Set flag=1 go to step 7 Else Move to next data element i= i+1;
Step 8: If(flag=1) then Return i as position of target located Else Report as target not
found.
Step 9: Stop.
_____________________________________________________________________________
Program for Linear Search
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
Time Complexity:
In Average case the comparisons required to find the location of element is approximately
equal to half of the number of elements in the array. In worst case the entire array is search.
So it requires N comparisons. Thus the time complexity in worst case is O(N).
___________________________________________________________________________________________
Binary search technique is very fast and efficient. It requires the list of elements to be in
sorted order.
In this method, to search an element we compare it with the element present at the centre
of the list. If it matches then the search is successful, otherwise the list is divided into two
halves – one from the 0th element to the center element (first half) and another from the
center element to the last element (second half).
As a result all the elements in first half are smaller than centre element whereas all the
elements in second half are greater than the center element.
Check whether target element is greater or smaller than center element. If element is smaller
then center element searching is done in first half, otherwise it is done on second half and
process is continued.
__________________________________________________________________________________________________
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
__________________________________________________________________________________________________
Example 2:
To search element = 3
0 1 2 3 4 5 6 7 8 9
1 2 3 10 11 13 16 21 46 73
L M U
M= (L + U)/2 = (0+9)/2 = 4
i.e 11 ! = 3
11>3 shift U to M-1
0 1 2 3 4 5 6 7 8 9
1 2 3 10 11 13 16 21 46 73
L M U
M= (L + U)/2 = (0+3)/2 = 1
i.e 2 ! = 3
2< 3 shift L to M+1
0 1 2 3 4 5 6 7 8 9
1 2 3 10 11 13 16 21 46 73
L,M U
M= (L + U)/2 = (2+3)/2 = 2
i.e 3 = 3
Element is found at location 2
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
__________________________________________________________________________________________________
__________________________________________________________________________________________________
__________________________________________________________________________________________________
#include<stdio.h>
#include<conio.h>
void main()
int e,n,i,a[10],mid=0,beg,end,flag=0;
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
clrscr();
printf("Enter n Element");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&e);
beg=0;
end=n-1;
while(beg<end)
mid=(beg+end)/2;
if(e==a[mid])
printf("No is present");
flag=flag+1;
break;
else if(e<a[mid])
end=mid-1;
}
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
else if(e>a[mid])
beg=mid+1;
if(flag==0)
printf("No is absent");
getch();
\\OUTPUT\\
Enter n Element:10
No is present
__________________________________________________________________________________________________
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
Difficult to insert to
5. Inserting operation Easy to insert
maintain sorted order.
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
Sorting Methods
Sorting refers to the operation of arranging a set of data in some given order. A collection of records is
called a list, where each record contains one or more fields. The field which contains unique value for each
record is known as the key field. For example, the record of students contains three fields (rollno, name,
address) in which rollno is a unique called a key.
__________________________________________________________________________________________________
It focuses on bringing the largest element to the end of the list with each successive
pass. The algorithm processes the list in passes. A list with n elements requires n-1
passes for sorting.
The algorithm in bubble sort involves two steps, executed over and over until the data is sorted.
1. Compare two adjacent items.
2. If necessary, swap (exchange) them.
In this sorting method, to arrange elements in ascending order, we begin with 0 th element and
compare it with the 1st element.
If it is found to be greater than 1st element then they are interchanged. Compare 1st element
with 2nd element and so on. In this way all the elements 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 second largest element gets placed at the second last position and so on.
As a result after all the iterations the last becomes a sorted list.
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
__________________________________________________________________________________________________
Example 1:
1st Iteration
23 15 29 11 1
Exchange 15 < 23
15 23 29 11 1
No Exchange
15 23 29 11 1
Exchange 11 < 29
15 23 11 29 1
Exchange 1 < 29
15 23 11 1 29
2nd Iteration
15 23 11 1 29
No Exchange
15 23 11 1 29
Exchange 11 < 23
15 11 23 1 29
Exchange 1 < 23
15 11 1 23 29
No Exchange
15 11 1 23 29
3rd Iteration
15 11 1 23 29
Exchange 11 < 15
11 15 1 23 29
Exchange 1 < 15
11 1 15 23 29
No Exchange
11 1 15 23 29
No Exchange
11 1 15 23 29
4th Iteration
11 1 15 23 29
Exchange 1 < 11
1 11 15 23 29
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
Array is Sorted
__________________________________________________________________________________________________
Advantage of bubble sort
It is easy to understand and implement.
Better efficiency.
__________________________________________________________________________________________________
__________________________________________________________________________________________________
#include<stdio.h>
#include<conio.h>
void main()
int a[5],i,j,temp;
clrscr();
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
printf("Enter Elements in array");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=0;i<5;i++)
{
for(j=0;j<4;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(i=0;i<5;i++)
printf("%d", a[i]);
getch();
\\OUTPUT\\
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
__________________________________________________________________________________________________
The selection sort is the easiest method of sorting. In this sort the data is arranged in ascending order. The
0th element is compared with all other elements, if the 0th element is found to be greater than the compared
element then they are interchanged. In this way after the first iteration the smallest element is placed at 0th
position. The procedure is repeated for 1st element and so on.
Pass 1: In pass 1, 0th element is compared with all other elements. (ie. 1st, 2nd, 3rd, and 4th)
Pass 2: In pass2, 1st element is compared with all other elements. (ie. 2nd, 3rd, and 4th)
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
Pass 4: In pass 4, 3rd element is compared with all other elements. (ie. 4th)
__________________________________________________________________________________________________
Advantage of selection sort
Simple and easy to understand.
Does not require additional memory space.
__________________________________________________________________________________________________
__________________________________________________________________________________________________
#include<stdio.h>
#include<conio.h>
void main()
int i,j,temp,a[5];
clrscr();
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=0;i<4;i++)
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
{
for(j=i+1;j<5;j++)
if(a[i]>a[j])
temp=a[i];
a[i]=a[j];
a[j]=temp;
for(i=0;i<5;i++)
printf("%d",a[i]);
getch();
\\OUTPUT\\
__________________________________________________________________________________________________
The insertion sort is substantially better than bubble sort. It is about twice as fast as the bubble sort.
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
It is also not too complex, although it is slightly more involved than the bubble sort. It is often used
as the final stage of more sophisticated sorts, such as quick sort.
Insertion sort is performed by inserting a particular element at the appropriate position. In insertion
sort, the first iteration starts with comparison of 1st element with the 0th element.
In the second iteration, 2nd element is compared with the 0th and 1st element. In general in every
iteration, an element is compared with all elements.
If at same point it is found that the element can be inserted at a 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.
__________________________________________________________________________________________________
Example of insertion sort: Array [ 15 9 30 10 1]
Pass 1: 1st element is compared with all previous elements ( ie. 0th)
Pass2: 2nd element is compared with all previous elements (ie, 0th and 1st )
Pass3: 3rd element is compared with all previous elements (ie, 0th, 1st and 2nd )
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
Pass4: 4th element is compared with all previous elements (ie, 0th, 1st , 2nd and 3rd )
________________________________________________________________________________________________
__________________________________________________________________________________________________
#include<stdio.h>
#include<conio.h>
void main()
int a[5],i,j,k,temp;
clrscr();
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
printf("Enter Array Elements:");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=1;i<5;i++)
temp=a[i];
j=i-1;
while((j>=0)&&(a[j]>temp))
a[j+1]=a[j];
j=j-1;
a[j+1]=temp;
for(i=0;i<5;i++)
printf("%d",a[i]);
getch();
\\OUTPUT\\
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
Quick sort is very popular sorting method. It was introduced by Haore in 1962. It is very
important method of internal sorting.
According to this algorithm, it is faster and easier to sort two small arrays than one large
one. The strategy that quick sort follows is of divide and conquer.
In this approach, numbers are divided and again subdivided and division goes on until it is
not possible to divide them further.
The procedure it follows is of recursion. It is also known as Partition Exchange Sort. I
n the below figure, * indicates pivot element and @ indicates the element whose position is
finalized.
Quick sort algorithm contains mainly three parts;
__________________________________________________________________________________________________
Algorithm for quick sort
1. In 1st iteration, the 0th element 10 is placed at its final position and the array is divided. Two index
variables a and b are taken to divide the array. The indexes are initialized in a way such that a refers
to 1st element 1 and b refers to (n 1)th element 2.
2. A search an element that is greater than value of 0th location. So a is incremented by one till the
value stored at a is greater than 0th element, it is incremented till 11, as 11 is greater than 10.
3. Similarly b search an element that is smaller than 0th element. So b is decremented by one till the
value stored at b is smaller than the value at 0th location. In our case, b is not decremented because
2 is less than 10.
4. When these elements are found, they are interchanged. Again from the current positions, a and b
are incremented and decremented respectively and exchanges are made appropriately if desired.
5. The process ends whenever the index pointers meet. In our case they are crossed at the value 0 and
20 for the indexes a and b respectively. Finally the 0th element 10 is interchanged with the value of
index b i.e. 0. The position b is now the final position of the pivot element 10.
6. As a result the whole array is divided into two parts where all the elements before 10 are less than
10 and all the element after 10 are greater than 10.
The same procedure is applied for two sub arrays. As a result at the end when all sub arrays are left
with one element, the original array becomes sorted.
__________________________________________________________________________________________________
Example:
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
10 1 9 11 46 20 15 0 72 2
* a b
Increment a by 1
10 1 9 11 46 20 15 0 72 2
* a b
Increment a by 1
10 1 9 11 46 20 15 0 72 2
* a b
Increment a by 1
Since a>* and b<* Swap a and b
10 1 9 2 46 20 15 0 72 11
* a b
Decrement b by 1
10 1 9 2 46 20 15 0 72 11
* a b
10 1 9 2 0 20 15 46 72 11
* a b
Decrement b by 1
10 1 9 2 0 20 15 46 72 11
* a,b
10 1 9 2 0 20 15 46 72 11
* b a
0 1 9 2 10 20 15 46 72 11
*
Now pivot element ie 10 is placed at its final position and array is divided in two subarray
And apply same procedure for subarrays.
20 15 46 72 11
0 1 9 2 10
* a b * a b
0 1 9 2 20 11 46 72 15
* a b 10 * a b
20 11 46 72 15
0 1 9 2 10 * a b
* a, b
20 11 15 72 46
0 1 9 2 10 * a b
*,b a
20 11 15 72 46
10
* a, b
0 1 9 2
* a b
0 1 9 2 10 20 11 15 72 46
* a, b * a, b
0 1 9 2 10 15 11 20 72 46
0 1 2 9 10 11 15 20 46 72
_______________________________________________________________________________________________
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
Not well suited for large size lists.
Little complex.
__________________________________________________________________________________________________
The radix sort is used generally when we intend to sort a large list of names alphabetically. Radix
in this case can be 26, as there are 26 alphabets.
If we want to arrange a list of names we can classify names into 26 classes, where the first class
consists of those names starting with ‘A’ and second class consists of names starting with ‘B’ and
so on. All this is done in first iteration. In second iteration each class is alphabetized according to
the second letter of the name and so on.
The radix sort method is used by a card sorter. A card sorter contains 13 receiving pockets labeled
as follows.
9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 11, 12, R(Reject)
The radix sort is based on the values of the actual digits in the positional representation ex. The
number 235 in decimal notation is written with a 2 in a hundred’s position, 3 is ten’s position and
5 in the unit’s position.
The sorter used above uses decimal numbers where the radix is 10 and hence uses only the first 10
pockets of the sorter. To sort element in ascending order, collect element from bucket no. 0 to 9
and to sort element in descending order, collect element from bucket no. 9 to 0 from top to botton.
______________________________________________________________________________________________
Example:
First Iteration
Inputs Pockets
0 1 2 3 4 5 6 7 8 9
242 242
986 986
504 504
428 428
321 321
Second Iteration
Inputs Pockets
0 1 2 3 4 5 6 7 8 9
428 428
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
986 986
504 504
242 242
321 321
Third Iteration
Inputs Pockets
0 1 2 3 4 5 6 7 8 9
986 986
242 242
428 428
321 321
504 504
__________________________________________________________________________________________________
Algorithms for radix sort
1. In first iteration the elements are picked up and kept in various pockets checking their unit's digit.
2. The cards are collected from pocket 9 to pocket 0 and again they are given as input to the sorter.
3. In second iteration the ten’s digits are sorted.
4. Repeat through step 2.
5. In the third iteration the digits at hundred’s position are sorted.
6. Repeat through step 2.
__________________________________________________________________________________________________
Fast when the keys are short i.e. when the range of the array elements is less.
Used in suffix array construction algorithms.
Time complexity : Number of comparisons require for radix sort algorithm in the worst case f(n)=O(n 2)
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
and in best case f(n)=O(n log2 n)
__________________________________________________________________________________________________
4. Best case
O (n) O (n2)
complexity
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
MSBTE Questions
Winter 2018
1. Describe working of linear search with example. 4M
2. Find the position of element 29 using binary search method in an array 4M
‘A’ given below. Show each step.
A = {11, 5, 21, 3, 29, 17, 2, 43}
3. Describe working of bubble sort with example. 4M
4. Describe working of selection sort method. Also sort given input list in 4M
ascending order using selection sort input list – 55, 25, 5, 15, 35.
Summer 2019
1. Explain the working of Binary search with an example. 4M
2. Sort the following numbers in ascending order using quick sort. Given 4M
numbers 50, 2, 6, 22, 3, 39, 49, 25, 18, 5
3. Differentiate between binary search and sequential search (linear 4M
search).
4. Sort the following numbers in ascending order using Bubble sort. 4M
Given numbers: 29, 35, 3, 8, 11, 15, 56, 12, 1, 4, 85, 5 & write the
output after each interaction.
Winter 2019
1. Sort the given numbers in ascending order using Radix sort: 348, 14, 4M
641, 3851, 74
2. Draw a binary search tree for the given numbers: 50, 33, 44, 22, 77, 35, 4M
60, 40
3. Implement a ‘C’ program to search a particular data from the given 4M
array using Linear Search.
4. Find the position of element 21 using Binary Search method in Array 4M
‘A’ given below: A = {11, 5, 21, 3, 29, 17, 2, 45}
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
1. Consider an array A = {23, 16, 5, 105, 64, 10} (May 2003)
Apply merge sort algorithm to
(a) Indicate the status of array A at the end of first pass.
(b) Total number of passes required to sort the array.
Sol. :
(a) The status of array A at the end of first pass : 23, 16, 105, 64, 10
(b) The total number of passed required to sort the array is 6.
Pass-3
5 5 5
16 16 16
23 23 23
10 10 10
64 64 64
105 105 105
Pass-4
5 5
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
16 16
10 10
23 23
64 64
105 105
Pass-5
5
10
16
23
64
105
Result : Sorted Array
5
10
16
23
64
105
(a) Total number of passes required to sort the array A is 5.
(b) The total number of exchanges carried out in the first pass are five.
3. Consider the array A={23, 16, 5, 105, 64, 125, 10, 18, 40, 20} (Nov. 2003)
Find the number of comparisons necessary to locate the position of the element fifteen(15) in
the given array or to indicate that element 15 is not present in the array, using Linear Search
Technique.
Sol. : By using linear search technique to search 15 element.
Take first element from array i.e. 23 compare with 15. It is not same that is to be searched. So take
second element i.e. 16, compare with 15. It is not also the same. Like this take one by one element from
array and compare with 15 each and check. The given array does not contain number 15 so the message is
print “Search Not Found” or “Element 15 not present in Array”.
4. Find the position of element 64 using Binary search technique in array A given below : A={
5, 16, 23, 64, 95, 105, 125, 150}
Mention the positions of ‘L’ (Lower Bound), ‘U’ (Upper Bound) and ‘M’ (Middle element)
at the end of each iteration. (Nov. 2003)
Sol. : Given array A={ 5, 16, 23, 64, 95, 105, 125, 150}
Now finding the position of element 64
Let L=1, U=8, M=5
M=(L+U)/2 = (1+8)/2 = 4
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
Here A[M]=95
Since 64 is less than 95 so change U=M-1 = 5-1= 4.
Here A[M]=64
Hence the required position of element 64 is 4.
5. Arrange the data elements in ascending order for array A given below, using Radix Sort
technique.
A={ 1234, 348, 143, 423, 76, 5} Give the following details of the Radix sort algorithm
1. Working and contents of array at the end of each pass.
2. Complexity (for average and worst cases). (Nov. 2003)
Origin Bucket 1st Merge 2nd Merge 3rd Merge 4th Merge
348,423
6 76 76
8 348
6. Find the position of element 99 using Linear search method in array given below :
A = {60, 20, 10, 99, 120} (4m, April 2004)
Sol. : Given array A={60, 20, 10, 99, 120}
To find no=99
1. POS=1
If (no==A[0] ) i.e. (99==60)
Position=1
Exit
Else
2. POS=2
If (no==A[1] ) i.e. (99==20)
Position=2
Exit
Else
3. POS=3
If (no==A[2] ) i.e. (99==10)
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
Position=3
Exit
Else
4. POS=4
If (no==A[3] ) i.e. (99==99)
Position=4
Stop
So the position of 99 is 4th element in array.
This search is applicable to a table organized While applying binary search, the elements
either as an array or a linked list. must be sorted.
The comparison of items will start from first The array to be searched is divided into two
element to last element. parts using the formula.
This search technique will require more time as This search is much efficient and powerful
compared to binary search. technique.
Used for single/multidimensional array Used for only single dimensional array
49 36 87 10 91 18 15 52 73
49 36 10 91 18 15 52 73 87
49 36 73 10 91 18 15 52 87
49 36 73 10 18 15 52 91 87
49 36 73 10 52 18 15 91 87
*
49 36 73 10 52 18 15 85 91 87
ARRAY 1 ARRAY 2
After finding the exact position of pivot element 85, array is divided into two sub-array. Array 1 contains
element less than 85 and array 2 contains element greater than 85. continue the sorting procedure till all
element are to be sorted
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
program by specifying the sort criteria and that coding the program. Moreover you can change
the program need to be compiled and linked. the sort criteria just by changing the sort
parameters that passed thru the SYSIN card.
Internal sort is not an efficient External sort is more efficient
It is slow process It is a faster process
Its take more time It takes less time
Internal sort gives you data handling flexibility Large amount of space will be required in
and its take less secondary memory external sort
Internal sorting is used for small volumes of External sorting is used for huge volume of
data data
Internal sort is simple External sort is more complicated
12. Find the position of element 64 using Linear search method in array A given below :
A = {23, 16, 5, 105, 64,125} (8m, Dec 2004)
Sol. : Given array A={23, 16, 5, 105, 64, 125}
To find no=64
1. POS=1
If (no==A[0] ) i.e. (64==23)
Position=1
Exit
Else
2. POS=2
If (no==A[1] ) i.e. (64==16)
Position=2
Exit
Else
3. POS=3
If (no==A[2] ) i.e. (64==5)
Position=3
Exit
Else
4. POS=4
If (no==A[3] ) i.e. (64==105)
Position=4
Exit
Else
5. POS=5
If (no==A[4] ) i.e. (64==64)
Position=5
Stop
So the position of 64 is 5th element in array.
SUSHAMA PAWAR
DSU Chapter 2: Searching and Sorting
EXERCISES
1. Compare the performance of selection and insertion sort.
2. For array elements given below, show trace of
(a) Bubble Sort (b) Selection Sort (d) Radix Sort algorithms
5, 22, 17, 35, 38, 28, 40, 42
3. Explain insertion sorting, state its advantages and disadvantages. Write a program to arrange
given ‘N’ numbers in ascending order using insertion sort
A={65, 32, 39, 21, 54, 85, 61, 16, 83, 45} (April 2005-8m)
4. Compare linear search and binary search techniques (minimum 4 points of comparison)
(Nov. 2004 – 4m)
5. Find the position of 46 using linear search method in array A given below
A={ 32, 16, 5, 51, 46, 70} (April. 2005 -8m)
6. Consider an array A={5, 16, 24, 64, 96, 106, 125, 150}. Find the number of comparisons
necessary to locate position of element 96 in the given array using binary search techniques
(April-May 2003 -4m)
7.Write a program in ‘C’ language for selection sort and arrange the given numbers in
ascending order using selection sort. Numbers: 16, 23, 16, 9, 7, 5 (8m, May-08)
8. Explain Binary Search algorithm and also give its advantages (4m, May-08)
SUSHAMA PAWAR