CH2 Searching and Sorting Notes
CH2 Searching and Sorting Notes
1. Linear Search
2. Binary Search
The above figure shows how sequential search works. It searches an element or value from an array
till the desired element or value is not found. If we search the element 25, it will go step by step in a
sequence order. It searches in a sequence order. Sequential search is applied on the unsorted or
unordered list when there are fewer elements in a list.
Algorithm
LinearSearch ( Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
1
Prepared by Mr. Raushan Kumar Guest Lecturer CSE Department
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Government Polytechnic Banka
Lecture notes for Data Structure and Algorithm
Here, we have
A[7]={5,2,1,6,3,7,8}
X=7
….
Linear search is rarely used practically. The time complexity of above algorithm is O(n).
{
int arr[50], search, cnt, num;
return 0;
}
1. We start by comparing the element to be searched with the element in the middle of the list/array.
2. If we get a match, we return the index of the middle element.
3. If we do not get a match, we check whether the element to be searched is less or greater than
in value than the middle element.
3
Prepared by Mr. Raushan Kumar Guest Lecturer CSE Department
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Government Polytechnic Banka
Lecture notes for Data Structure and Algorithm
4. If the element/number to be searched is greater in value than the middle number, then we pick
the elements on the right side of the middle element(as the list/array is sorted, hence on the
right, we will have all the numbers greater than the middle number), and start again from the
step 1.
5. If the element/number to be searched is lesser in value than the middle number, then we pick
the elements on the left side of the middle element, and start again from the step 1.
Binary Search is useful when there are large number of elements in an array and they are sorted.
So a necessary condition for Binary search to work is that the list/array should be sorted.
The above array is sorted in ascending order. As we know binary search is applied on sorted
lists only for fast searching.
For example, if searching an element 25 in the 7-element array, following figure shows how binary
search works:
Binary searching starts with middle element. If the element is equal to the element that we
are searching then return true. If the element is less than then move to the right of the list or if
the element is greater than then move to the left of the list. Repeat this, till you find an
element.
Algorithm
Step 5: If target > list[mid], discard 1/2 of list between list[first] and list[mid].
Step 6: Continue searching the shortened list until either the target is found, or there are no elements t
o probe.
5
Prepared by Mr. Raushan Kumar Guest Lecturer CSE Department
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Government Polytechnic Banka
Lecture notes for Data Structure and Algorithm
Here, we have
A[16]={1,2,3,4,6,7,8,10,12,13,15,16,18,19,20,22}
X=19
Let us first divide it into two smaller arrays of 8 items each. The first 8 items in a sub array and
another 8 in another sub array. A1={1,2,3,4,6,7,8,10} and A2={12,13,15,16,18,19,20,22}
As 10 and 12 are the middle items of this ordered array, we know 19 is greater than the middle
numbers that means we don’t require to look for the targeted item in first sub array. Let us search in
the second subarray A2={12,13,15,16,18,19,20,22}
In the second array we have 8 items. Let’s divide them into two equal arrays and check the middle
items. Here the middle items are 16 and 18. As 19 is greater than both of them, we don’t need to look
in the first four items of this subarray. A21={12,13,15,15} and A22={18,19,20,22}
Let us look in the last four items sub array A22={18,19,20,22}. Let us again divide it to subarrays
A221={18,19) and A222={20,22}. Here the middle items are 19 and 20. Hence, we found the target
item 19 in first subarray.
void main()
{
int f, l, m, size, i, sElement, list[50]; //int f, l ,m : First, Last, Middle
clrscr();
f = 0;
6
Prepared by Mr. Raushan Kumar Guest Lecturer CSE Department
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Government Polytechnic Banka
Lecture notes for Data Structure and Algorithm
l = size - 1;
m = (f+l)/2;
while (f <= l) {
if (list[m] < sElement)
f = m + 1;
else if (list[m] == sElement)
{ printf("Element found at index %d.\
n",m); break;
}
else
l = m - 1;
m = (f + l)/2;
}
if (f > l)
printf("Element Not found in the list.");
getch();
}
Sorting:
Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to
arrange data in a particular order.
Bubble Sort
Bubble sort is the simplest sorting algorithm. It is based on comparison where each adjacent pair of
element is compared and swapped if they are not in order. It works by repeatedly stepping through
the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order.
The pass through the list is repeated until no swaps are needed, which means the list is sorted. This
algorithm is not suitable for huge data sets. Average and worst case time complexity of this
algorithm are of Ο(n2) where n is the number of items.
Algorithm
for i=N-1 to 2 {
set swap flag to false for
j=1 to i {
if list[j-1] > list[j]
swap list[j-1] and list[j]
set swap flag to true
}
if swap flag is false, break. The list is sorted.
}
7
Prepared by Mr. Raushan Kumar Guest Lecturer CSE Department
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Government Polytechnic Banka
Lecture notes for Data Structure and Algorithm
[NOTE: In each pass, the largest item “bubbles” down the list until it settles in its final position. This
is where bubble sort gets its name.]
Example,
Suppose we have a list of array of 5 elements A[5]={40,50,30,20,10}. We have to sort this array
using bubble sort algorithm.
We observe in algorithm that Bubble Sort compares each pair of array element unless the whole
array is completely sorted in an ascending order. After every iteration the highest values settles
down at the end of the array. Hence, the next iteration need not include already sorted elements.
In the bubble sort, elements are swapped in place The bubble sort requires n-squared processing steps
without using additional temporary storage. for every n number of elements to be sorted.
8
Prepared by Mr. Raushan Kumar Guest Lecturer CSE Department
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Government Polytechnic Banka
Lecture notes for Data Structure and Algorithm
The space requirement is at a minimum The bubble sort is mostly suitable for academic
teaching but not for real-life applications.
Selection Sort
Selection sort is an in-place comparison sort algorithm. In this algorithm, we repeatedly select the
smallest remaining element and move it to the end of a growing sorted list. It is one of the simplest
sorting algorithm. Selection sort is known for its simplicity. It has performance advantages over
more complicated algorithms in certain situations.
This algorithm is not suitable for large data sets as its average and worst case complexities are
of Ο(n2), where n is the number of items.
Algorithm
Example,
Let us assume an array A[10]={45,20,40,05,15,25,50,35,30,10}. We have to sort this array using
selection sort.
In this algorithm we have to find the minimum value in the list first. Then, Swap it with the value
in the first position. After that, Start from the second position and repeat the steps above for
remainder of the list.
Insertion Sort
Insertion sort is an in-place sorting algorithm based on comparison. It is a simple algorithm where a
sorted sub list is maintained by entering on element at a time. An element which is to be inserted in
this sorted sub-list has to find its appropriate location and then it has to be inserted there. That is the
reason why it is named so. This algorithm is not suitable for large data set.
Average and worst case time complexity of the algorithm is Ο(n2), where n is the number of items.
Algorithm
Example,
Let us take an example of an array A[6]={20,10,30,15,25,05}. We have to sort this array using
insertion sort.
Advantages Disadvantages
The main advantage of the insertion sort is its simplicity. The disadvantage of the insertion sort is that it does not
perform as well as other, better sorting algorithms
It also exhibits a good performance when dealing with With n-squared steps required for every n element to
a small list. be sorted, the insertion sort does not deal well with a
huge list.
11
Prepared by Mr. Raushan Kumar Guest Lecturer CSE Department
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Government Polytechnic Banka
Lecture notes for Data Structure and Algorithm
The insertion sort is an in-place sorting algorithm so the The insertion sort is particularly useful only when sorting
space requirement is minimal. a list of few items.
Quick Sort
Quick sort is a well-known sorting algorithm. It is highly efficient and also known as partition
exchange sort. In this sorting algorithm the array is divided into 2 sub array. One contain smaller
values than pivot value and other array contain elements having greater values than pivot value.
Pivot is an element that is used to compare and divide the elements of the main array into two. Quick
sort partitions an array and then calls itself recursively twice to sort the two resulting sub arrays.
This algorithm is quite efficient for large data sets.
The Average and worst case complexity are of this algorithm is Ο(n2), where n is the number of
items.
Algorithm
In practice, quick sort is faster than other sorting algorithms because its inner loop can be efficiently
implemented on most architectures, and in most real-world data it is possible to make design choices
which minimize the possibility of require time.
Example,
Let us assume an array A[10]={42,37,11,98,36,72,65,10,88,78}. We have to sort this array using
quick sort.
12
Prepared by Mr. Raushan Kumar Guest Lecturer CSE Department
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Government Polytechnic Banka
Lecture notes for Data Structure and Algorithm
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
14
Prepared by Mr. Raushan Kumar Guest Lecturer CSE Department
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Government Polytechnic Banka
Lecture notes for Data Structure and Algorithm
Radix sort:
Algorithm:
For each digit i where i varies from the least significant digit to the most significant digit of a number
Sort input array using count sort algorithm according to ith digit.
15
Prepared by Mr. Raushan Kumar Guest Lecturer CSE Department
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Government Polytechnic Banka
Lecture notes for Data Structure and Algorithm
2: 21 123
3: 34
4: 44
5: 654
6:
7:
8:
9:
The array becomes : 10,11,17,21,34,44,123,654 which is sorted. This is how our algorithm works.
Advantages
1. It is implemented in Java, it would be faster than quicksort or heap.
2. It is stable because it preserves existing order of equals keys.
3. It is good on small keys.
Disadvantages
1. It is not efficient on very long keys because the total sorting time is proportional to key
length and to the number of items to sort.
2. We have to write an unconventional compare routine.
3. It requires fixed size keys and some standard way of breaking the keys to pieces.
16
Prepared by Mr. Raushan Kumar Guest Lecturer CSE Department