0% found this document useful (0 votes)
16 views19 pages

CPDS - 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views19 pages

CPDS - 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

5.

2 Sorting and Searching Techniques

5
There are many techniques by using which, sorting can be performed
Sorting
Sl. No. Description
Algorithms
Insertion sort inserts each element of the array to its
1 Insertion Sort proper place. It is a very simple sort method which is used
to arrange the deck of cards while playing bridge
SORTING AND SEARCHING TECHNIQUES Quick sort follows the divide and conquer approach in
which the algorithm is breaking down into sub problems,
Insertion Sort – Quick Sort – Heap Sort – Merge Sort –Linear Search – Binary Search 2 Quick Sort
then solving the sub problems, and combining the results
back together to solve the original problem.
In the heap sort, Min heap or max heap is maintained
from the array elements depending upon the choice and
5.1 INTRODUCTION TO SORTING 3 Heap Sort
the elements are sorted by deleting the root element of the
➢ Sorting is the process of arranging the elements of an array so that they can be heap.
placed either in ascending or descending order. Efficient sorting is important to
optimizing the use of other algorithms that require sorted lists to work correctly Merge sort follows divide and conquer approach in
and for producing human – read able input which, the list is first divided into the sets of equal
4 Merge Sort elements and then each half of the list is sorted by using
For example,
merge sort. The sorted list is combined again to form an
elementary sorted array

5.2. INSERTION SORT


➢ Insertion sort is a simple sorting algorithm.
➢ This sorting method sorts the array by shifting elements one by one.
➢ It builds the final sorted array one item at a time.
➢ Insertion sort has one of the simplest implementation.
➢ This sort is efficient for smaller data sets but it is insufficient for larger lists.
➢ It has less space complexity like bubble sort.
➢ It requires single additional memory space.
➢ Insertion sort does not change the relative order of elements with equal keys
because it is stable.
C Programming and Data Structures 5.3 5.4 Sorting and Searching Techniques

5.2.1 Algorithm: ➢ At the first step, 40 has nothing before it. Element 10 is compared to 40 and is
inserted before 40. Element 9 is smaller than 40 and 10, so it is inserted before 10
Step 1 − If the element is the first one, it is already sorted. and this operation continues until the array is sorted in ascending order.
Step 2 – Move to next element 5.2.3 Analysis of Insertion Sort:
Step 3 − Compare the current element with all elements in the sorted array Time Complexity
Step 4 – If the element in the sorted array is smaller than the current element, iterate to Best O(n)
the next element. Otherwise, shift all the greater element in the array by one Worst O(n2)
position towards right
Average O(n2)
Step 5 − Insert the value at the correct position
Space Complexity O(1)
Step 6 − Repeat until the complete list is sorted
Stability Yes
5.2.2 Working of Insertion sort Algorithm
Consider an unsorted array of elements 40, 10, 9, 20, 30, 50 5.2.4 Applications
➢ The insertion sort is used when:
 The array is has a small number of elements
 There are only a few elements left to be sorted
Example Program 5.1
#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);
➢ The above steps represents how insertion sort works. Insertion sort works like the
}
way we sort playing cards in our hands. It always starts with the second element
as key. The key is compared with the elements ahead of it and is put it in the right for (c = 1 ; c <= n - 1; c++)
place. {
C Programming and Data 5.6 Sorting and Searching Techniques
Structures 5.5
d = c; 40
while ( d > 0 && array[d] < array[d-1]) 40
{
5.3 QUICK SORT
t = array[d];
➢ Quick sort is also known as Partition-exchange sort based on the rule of Divide
array[d] = array[d-1]; and Conquer.
array[d-1] = t; ➢ It is a highly efficient sorting algorithm.
d--; ➢ Quick sort is the quickest comparison-based sorting algorithm.
} ➢ It is very fast and requires less additional space, only O(n log n) space is required.
} ➢ Quick sort picks an element as pivot and partitions the array around the picked
pivot.
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++) 5.3.1 Algorithm for Quick Sort:
{ Step 1: Choose the highest index value as pivot.
printf("%d\n", array[c]); Step 2: Take two variables to point left and right of the list excluding pivot.
} Step 3: Left points to the low index.
return 0; Step 4: Right points to the high index.
} Step 5: While value at left < (Less than) pivot move right.
Output Step 6: While value at right > (Greater than) pivot move left.
Step 7: If both Step 5 and Step 6 does not match, swap left and right.
Enter the number of elements Step 8: If left = (Less than or Equal to) right, the point where they met is new pivot.
5
5.3.2 Working of Quick sort Algorithm
Enter 5 integers
Consider an unsorted array as follows
40
36, 34, 43, 11, 15, 20, 28, 45, 27, 32
30
➢ The following steps represents how to find the pivot value in an array. As we see,
20 pivot value divides the list into two parts (partitions) and then each part is
10 processed for quick sort. Quick sort is a recursive function. We can call the
partition function again.
40
Sorted list in ascending order
10
20
30
C Programming and Data Structures 5.7
5.8 Sorting and Searching Techniques

5.3.3 Quicksort Complexity


Time Complexity
Best O(n*log n)
Worst O(n2)
Average O(n*log n)
Space Complexity O(log n)
Stability No

5.3.4 Applications of quick sort:


Quicksort algorithm is used when
➢ the programming language is good for recursion
➢ time complexity matters
➢ space complexity matters
Example Program 5.2: Program for implementing Quick Sort
#include<stdio.h>
#include<conio.h>
//quick Sort function to Sort Integer array list
void quicksort(int array[], int firstIndex, int lastIndex)
{
//declaaring index variables
int pivotIndex, temp, index1, index2;
if(firstIndex < lastIndex)
{
//assigninh first element index as pivot element
pivotIndex = firstIndex;
index1 = firstIndex;
index2 = lastIndex;
//Sorting in Ascending order with quick sort
C Programming and Data Structures 5.9 5.10 Sorting and Searching Techniques
while(index1 < index2) //Declaring variables
{ int array[100],n,i;
//Number of elements in array form user input
while(array[index1] <= array[pivotIndex] && index1 < lastIndex)
printf("Enter the number of element you want to Sort : ");
{
scanf("%d",&n);
index1++;
//code to ask to enter elements from user equal to n
}
printf("Enter Elements in the list : ");
while(array[index2]>array[pivotIndex])
for(i = 0; i < n; i++)
{
{
index2--;
scanf("%d",&array[i]);
}
}
if(index1<index2) //calling quickSort function defined above quicksort(array,0,n-1);
{ //print sorted array

//Swapping opertation printf("Sorted elements: ");

temp = array[index1]; for(i=0;i<n;i++)

array[index1] = array[index2]; printf(" %d",array[i]);

array[index2] = temp; getch();

} return 0;

}
//At the end of first iteration, swap pivot element with index2 element
}
temp = array[pivotIndex];
Output
array[pivotIndex] = array[index2];
Enter the number of element you want to sort: 5
array[index2] = temp;
Enter the elements in the list:
//Recursive call for quick sort, with partiontioning
7
quicksort(array, firstIndex, index2-1);
10
quicksort(array, index2+1, lastIndex);
3
}
21
}
15
int main()
Sorted elements: 3 7 10 15 21
{
C Programming and Data Structures 5.11 5.12 Sorting and Searching Techniques

5.4 HEAP SORT

➢ Heap sort is a comparison based sorting algorithm.


➢ It is a special tree-based data structure.
➢ Heap sort processes the elements by creating the min-heap or max-heap using the
elements of the given array
➢ Min-heap or max-heap represents the ordering of array in which the root element
represents the minimum or maximum element of the array
➢ Heap sort basically recursively performs two main operations
 Build a heap H, using the elements of array. After converting the given heap into max heap, the array elements are
 st
Repeatedly delete the root element of the heap formed in 1 phase.

5.4.1 What is a heap?


➢ A heap is a complete binary tree, and the binary tree is a tree in which the node ➢ Next step is to delete the root element (89) from the max heap. To delete this node,
can have the utmost two children. A complete binary tree is a binary tree in which swap it with the last node, i.e. (11). After deleting the root element, again heapify
all the levels except the last level, i.e., leaf node, should be completely filled, and it to convert it into max heap.
all the nodes should be left-justified.

5.4.2 Working of Heap sort Algorithm


➢ In heap sort, basically, there are two phases involved in the sorting of elements.
By using the heap sort algorithm, they are as follows:
➢ The first step includes the creation of a heap by adjusting the elements of the array.
➢ After the creation of heap, now remove the root element of the heap repeatedly by
shifting it to the end of the array, and then store the heap structure with the
remaining elements.
Consider an unsorted array as follows
➢ After swapping the array element 89 with 11, and converting the heap into max-
81, 89, 9, 11, 14, 76, 54, 22 heap, the elements of array are
Given array is

➢ In the next step, again delete the root element (81) from the max heap. To delete
First, construct a heap from the given array and convert it into max heap this node, swap it with the last node, i.e. (54). After deleting the root element,
again heapify it to convert it into max heap.
C Programming and Data Structures 5.13 5.14 Sorting and Searching Techniques

➢ After swapping the array element 81 with 54 and converting the heap into max-
➢ After swapping the array element 54 with 14 and converting the heap into max-
heap, the elements of array are
heap, the elements of array are

➢ In the next step, delete the root element (76) from the max heap again. To delete ➢ In the next step, again delete the root element (22) from the max heap. To delete
this node, swap it with the last node, i.e. (9). After deleting the root element, again this node, swap it with the last node, i.e. (11). After deleting the root element,
heapify it to convert it into max heap. again heapify it to convert it into max heap.

➢ After swapping the array element 22 with 11 and converting the heap into max-
➢ After swapping the array element 76 with 9 and converting the heap into max- heap, the elements of array are
heap, the elements of array are

➢ In the next step, again delete the root element (14) from the max heap. To delete
➢ In the next step, again delete the root element (54) from the max heap. To delete this node, swap it with the last node, i.e. (9). After deleting the root element, again
this node, swap it with the last node, i.e. (14). After deleting the root element, heapify it to convert it into max heap.
again heapify it to convert it into max heap.
C Programming and Data Structures 5.15 5.16 Sorting and Searching Techniques

5.4.3 Heapsort Complexity:


Time Complexity
Best O(n log n)
Worst O(n log n)
Average O(n log n)
Space Complexity O(1)
➢ After swapping the array element 14 with 9 and converting the heap into max-
heap, the elements of array are Stability No

5.4.4 Heap Sort Applications:


➢ Systems concerned with security and embedded systems such as Linux Kernel use
➢ In the next step, again delete the root element (11) from the max heap. To delete
Heap Sort.
this node, swap it with the last node, i.e. (9). After deleting the root element, again
heapify it to convert it into max heap. ➢ Because of the O(n log n) upper bound on Heapsort's running time and constant
O(1) upper bound on its auxiliary storage.
➢ Although Heap Sort has O(n log n) time complexity even for the worst case, it
doesn't have more applications ( compared to other sorting algorithms like Quick
Sort, Merge Sort ).
Example Program 5.3: Program for implementing Heap Sort
➢ After swapping the array element 11 with 9, the elements of array are
#include <stdio.h>
/* function to heapify a subtree. Here 'i' is the
index of root node in array a[], and 'n' is the size of heap. */
➢ Now, heap has only one element left. After deleting it, heap will be empty.
void heapify(int a[], int n, int i)
{
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left child
➢ After completion of sorting, the array elements are
int right = 2 * i + 2; // right child
// If left child is larger than root
if (left < n && a[left] > a[largest])
Now, the array is completely sorted largest = left;
C Programming and Data Structures 5.17 5.18 Sorting and Searching Techniques
// If right child is larger than root void printArr(int arr[], int n)
if (right < n && a[right] > a[largest]) {
largest = right; for (int i = 0; i < n; ++i)
// If root is not largest {
if (largest != i) { printf("%d", arr[i]);
// swap a[i] with a[largest] printf(" ");
int temp = a[i]; }
a[i] = a[largest]; }
a[largest] = temp; int main()
{
int a[] = {42, 8, 26, 39, 28, 23, 7};
heapify(a, n, largest); int n = sizeof(a) / sizeof(a[0]);
} printf("Before sorting array elements are - \n");
} printArr(a, n);
/*Function to implement the heap sort*/ heapSort(a, n);
void heapSort(int a[], int n)
printf("\nAfter sorting array elements are - \n");
{ printArr(a, n);
for (int i = n / 2 - 1; i >= 0; i--) return 0;
heapify(a, n, i); }
// One by one extract an element from heap Output
for (int i = n - 1; i >= 0; i--) {
/* Move current root element to end*/ Before sorting array elements are
// swap a[0] with a[i] 42, 8, 26, 39, 28, 23, 7
int temp = a[0]; After sorting array elements are
a[0] = a[i]; 7, 8, 23, 26, 28, 39, 42
a[i] = temp;
5.5 MERGE SORT
heapify(a, i, 0); ➢ Merge sort is a sorting technique based on divide and conquer technique.
} ➢ With worst-case time complexity being Ο(n log n), it is one of the most respected
} algorithms.
/* function to print the array elements */
C Programming and Data Structures 5.19 5.20 Sorting and Searching Techniques
➢ Merge sort first divides the array into equal halves and then combines them in a Now, combine them in the same manner they were broken. First compare the
sorted manner element of each array and then combine them into another array in sorted order.
5.5.1 Algorithm So, first compare 12 and 31, both are in sorted positions. Then compare 25 and 8,
➢ Merge sort keeps on dividing the list into equal halves until it can no more be and in the list of two values, put 8 first followed by 25. Then compare 32 and 17, sort
divided. By definition, if it is only one element in the list, it is sorted. Then, merge them and put 17 first followed by 32. After that, compare 40 and 42, and place them
sort combines the smaller sorted lists keeping the new list sorted too sequentially.

Step 1 − if it is only one element in the list it is already sorted, return.


Step 2 − divide the list recursively into two halves until it can no more be divided.
Step 3 − merge the smaller lists into new list in sorted order. In the next iteration of combining, now compare the arrays with two data values
5.5.2 Working of Merge sort Algorithm and merge them into an array of found values in sorted order.

Consider an unsorted array elements12, 31, 25, 8, 32, 17, 40 and 42


Let the elements of array are

Now, there is a final merging of the arrays. After the final merging of above
arrays, the array will look like
First divide the given array into two equal halves. Merge sort keeps dividing the
list into equal parts until it cannot be further divided.
As there are eight elements in the given array, so it is divided into two arrays of
size 4. 5.5.3 Merge sort complexity
Time Complexity
Best O(n*log n)
Worst O(n*logn)
Now, again divide these two arrays into halves. As they are of size 4, so divide
them into new arrays of size 2. Average O(n*logn)
Space Complexity O(n)
Stability YES

Now, again divide these arrays to get the atomic value that cannot be further
divided. 5.5.4 Merge Sort Applications
➢ Inversion count problem
➢ External sorting
➢ E-commerce applications
C Programming and Data Structures 5.21 5.22 Sorting and Searching Techniques
Example Program 5.4: Program for implementing Merge Sort k++;
#include <stdio.h> }
/* Function to merge the subarrays of a[] */ while (i<n1)
void merge(int a[], int beg, int mid, int end) {
{ a[k] = LeftArray[i];
int i, j, k; i++;
int n1 = mid - beg + 1; k++;
int n2 = end - mid; }
int LeftArray[n1], RightArray[n2]; //temporary arrays while (j<n2)
/* copy data to temp arrays */ {
for (int i = 0; i < n1; i++) a[k] = RightArray[j];
LeftArray[i] = a[beg + i]; j++;
for (int j = 0; j < n2; j++) k++;
RightArray[j] = a[mid + 1 + j]; }
i = 0; /* initial index of first sub-array */ }
j = 0; /* initial index of second sub-array */ void mergeSort(int a[], int beg, int end)
k = beg; /* initial index of merged sub-array */ {
while (i < n1 && j < n2) if (beg < end)
{ {
if(LeftArray[i] <= RightArray[j]) int mid = (beg + end) / 2;
{ mergeSort(a, beg, mid);
a[k] = LeftArray[i]; mergeSort(a, mid + 1, end);
i++; merge(a, beg, mid, end);
} }
else }
{ /* Function to print the array */
a[k] = RightArray[j]; void printArray(int a[], int n)
j++; {
} int i;
C Programming and Data Structures 5.23 5.24 Sorting and Searching Techniques
for (i = 0; i < n; i++) 5.6.1 Searching Methods
printf("%d ", a[i]); ➢ Searching in the data structure can be done by applying searching algorithms to
check for or extract an element from any form of stored data structure. These
printf("\n");
algorithms are classified according to the type of search operation they perform,
} such as:
➢ Sequential search - The list or array of elements is traversed sequentially while
int main() checking every component of the set. For example – Linear Search.
{ ➢ Interval Search - The interval search includes algorithms that are explicitly
int a[] = { 10, 35, 23, 5, 31, 19, 40, 43 }; designed for searching in sorted data structures. In terms of efficiency, these
int n = sizeof(a) / sizeof(a[0]); algorithms are far better than linear search algorithms. Example- Logarithmic
Search, Binary search.
printf("Before sorting array elements are - \n");
These methods are evaluated based on the time taken by an algorithm to search
printArray(a, n); an element matching the search item in the data collections and are given by,
mergeSort(a, 0, n - 1); ➢ The best possible time
printf("After sorting array elements are - \n"); ➢ The average time
printArray(a, n); ➢ The worst-case time
return 0; The primary concerns are with worst-case times, which provide guaranteed
predictions of the algorithm’s performance and are also easier to calculate than average
} times.
Output 5.7 LINEAR SEARCH
Before sorting array elements are ➢ Linear search is also called as sequential search algorithm.
10, 35, 23, 5, 31, 19, 40, 43 ➢ It is the simplest searching algorithm.
After sorting array elements are ➢ In Linear search, we simply traverse the list completely and match each element
of the list with the item whose location is to be found.
5, 10, 19, 23, 31, 35, 40, 43
➢ If the match is found, then the location of the item is returned; otherwise, the
5.6 INTRODUCTION TO SEARCHING algorithm returns NULL.
➢ Searching in data structure refers to the process of finding the required ➢ It is widely used to search an element from the unordered list, i.e., the list in which
information from a collection of items stored as elements in the computer items are not sorted.
memory. ➢ The worst-case time complexity of linear search is O (n).
➢ These sets of items are in different forms, such as an array, linked list, graph, or
tree. Another way to define searching in the data structures is by locating the
desired element of specific characteristics in a collection of items
C Programming and Data Structures 5.25 5.26 Sorting and Searching Techniques

5.7.1 Steps used in the implementation of Linear Search


➢ First, we have to traverse the array elements using for loop.
➢ In each iteration of for loop, compare the search element with the current array
element, and Let the element to be searched is K = 41
 If the element matches, then return the index of the corresponding array Now, start from the first element and compare K with each element of the array.
element.
 If the element does not match, then move to the next element.
➢ If there is no match or the search element is not present in the given array, return
-1.

5.7.2 Algorithm The value of K, i.e., 41, is not matched with the first element of the array. So, move to
Linear_Search(a, n, val) // 'a' is the given array, 'n' is the size of given array, 'val' the next element. And follow the same process until the respective element is found.
is the value to search
Step 1: set pos = -1
Step 2: set i = 1
Step 3: repeat step 4 while i <= n
Step 4: if a[i] == val
set pos = i
print pos
go to step 6
[end of if]
set ii = i + 1
[end of loop]
Step 5: if pos = -1
print "value is not present in the array "
[end of if]
Step 6: exit

5.7.3 Working of Linear search


Consider an array of elements 70, 40, 30, 11, 57, 41, 25, 14, 52
Let the elements of array are
C Programming and Data Structures 5.27 5.28 Sorting and Searching Techniques
Now, the element to be searched is found. So algorithm will return the index of {
the element matched. if (a[i] == val)
5.7.4 Linear Search complexity return i+1;
Time Complexity }
Best O(1) return -1;
Worst O(n) }
Average O(n) int main() {
Space Complexity O(1) int a[] = {59, 40, 33, 11, 57, 41, 27, 18, 53}; // given array
int val = 41; // value to be searched
5.7.5 Applications of Linear Search Algorithm int n = sizeof(a) / sizeof(a[0]); // size of array
➢ Linear search can be applied to both single-dimensional and multi-dimensional
int res = linearSearch(a, n, val); // Store result
arrays.
printf("The elements of the array are - ");
➢ Linear search is easy to implement and effective when the array contains only a
few elements. for (int i = 0; i < n; i++)

➢ Linear Search is also efficient when the search is performed to fetch a single printf("%d ", a[i]);
search in an unordered-List. printf("\nElement to be searched is - %d", val);
5.7.6 Advantages and Disadvantages if (res == -1)
Sl. No. Advantages Disadvantages printf("\nElement is not present in the array");
Will perform fast searches of Time consuming for the enormous else
1.
small to medium lists arrays. printf("\nElement is present at %d position of array", res);
2. The list does not need to sorted Slow searching of big lists return 0;
Not affected by insertions and A key element doesn't matches any }
3. deletions element then Linear search algorithm is Output
a worst case
The elements of the array are - 59, 40, 33, 11, 57, 41, 27, 18, 53
Example Program 5.5: Program for Implementation of Linear Search Element to be searched is – 41
#include <stdio.h> Element is present at 6 position of array
int linearSearch(int a[], int n, int val) { 5.8 BINARY SEARCH
// Going through array sequencially ➢ Binary search is the search technique that works efficiently on sorted lists.
for (int i = 0; i < n; i++) ➢ Hence, to search an element into some list using the binary search technique, we
must ensure that the list is sorted.
C Programming and Data Structures 5.29 5.30 Sorting and Searching Techniques
➢ Binary search follows the divide and conquer approach in which the list is divided ➢ There are two methods to implement the binary search algorithm -
into two halves, and the item is compared with the middle element of the list.  Iterative method
➢ If the match is found then, the location of the middle element is returned.
 Recursive method
➢ Otherwise, we search into either of the halves depending upon the result produced
The recursive method of binary search follows the divide and conquer approach
through the match.
Consider an array of elements 10, 12, 24, 29, 39, 40, 51, 56, 69
5.8.1 Algorithm Let the elements of array are
Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array,
'lower_bound' is the index of the first array element, 'upper_bound' is the index of the last
array element, 'val' is the value to search
Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
Step 2: repeat steps 3 and 4 while beg <=end
Let the element to search is, K = 56
Step 3: set mid = (beg + end)/2
Use the below formula to calculate the mid of the array
Step 4: if a[mid] = val
mid = (beg + end)/2
set pos = mid
In the given array beg = 0, end = 8. So mid = (0+8)/2 = 4
print pos
go to step 6
else if a[mid] > val
set end = mid - 1
else
set beg = mid + 1
[end of if]
[end of loop]
Step 5: if pos = -1
print "value is not present in the array"
[end of if]
Step 6: exit

5.8.2 Working of Binary search


➢ To understand the working of the Binary search algorithm, let's take a sorted array.
It will be easy to understand the working of Binary search with an example.
C Programming and Data Structures 5.31 5.32 Sorting and Searching Techniques
int mid;
if(end >= beg)
{ mid = (beg + end)/2;
/* if the item to be searched is present at middle */
if(a[mid] == val)
{
return mid+1;
Now, the element to search is found. So algorithm will return the index of the }
element matched.
/* if the item to be searched is smaller than middle, then it can only be in
5.8.3 Binary Search complexity: left subarray*/
Time Complexity else if(a[mid] < val)
Best O(1) {
return binarySearch(a, mid+1, end, val);
Worst O(logn)
}
Average O(logn)
/* if the item to be searched is greater than middle, then it can only be in
Space Complexity O(1) right subarray*/
else
5.8.4 Advantages and Disadvantages
{
Sl. No. Advantages Disadvantages
return binarySearch(a, beg, mid-1, val);
1. It is a much faster algorithm It can be used only when data is sorted
}
It works on the divide and It is more complicated
2. }
conquers principle
return -1;
It is efficient If random access is not supported then
3. }
efficiency might be lost
It is a simple algorithm to It can be implemented only for two-way int main() {
4.
understand transversal data structures int a[] = {21, 14, 35, 30, 40, 51, 55, 57, 70}; // given array
int val = 40; // value to be searched
Example Program 5.6: Program for implementation of Binary Search
int n = sizeof(a) / sizeof(a[0]); // size of array
#include <stdio.h>
int res = binarySearch(a, 0, n-1, val); // Store result
int binarySearch(int a[], int beg, int end, int val)
printf("The elements of the array are - ");
{
C Programming and Data Structures 5.33 5.34 Sorting and Searching Techniques
for (int i = 0; i < n; i++) REVIEW QUESTIONS
printf("%d ", a[i]); PART A
1. What is sorting?
printf("\nElement to be searched is - %d", val); if (res == -1)
printf("\nElement is not present in the array"); ➢ Sorting refers to arranging data in a particular format. Sorting algorithm specifies
the way to arrange data in a particular order.
else
2. Define insertion sort?
printf("\nElement is present at %d position of array", res);
➢ Successive element in the array to be sorted and inserted into its proper place
return 0; with respect to the other already sorted element. We start with second element
and put it in its correct place, so that the first and second elements of the array
are in order.
}
3. Write short notes on quick sort.
Output
➢ Quicksort is a divide-and-conquer algorithm. It works by selecting a 'pivot'
The elements of the array are - 21, 14, 35, 30, 40, 51, 55, 57, 70 element from the array and partitioning the other elements into two sub-arrays,
Element to be searched is – 40 according to whether they are less than or greater than the pivot. For this reason,
Element is present at 5 position of array it is sometimes called partition-exchange sort.
4. What is Time Complexity for Quick Sort?
5.8.5 Linear Search vs Binary Search
Sl.
Linear Search Binary Search
No.
In linear search input data need not In binary search input data need to be in
1.
to be in sorted. sorted order.
5. What is Merge sort?
2. It is also called sequential search. It is also called half-interval search.
➢ The Merge Sort function repeatedly divides the array into two halves until we
It is preferable for the small-sized It is preferable for the large-size data sets. reach a stage where we try to perform Merge Sort on a subarray of size 1
3.
data sets.
6. What is Time Complexity for Merge Sort?
The time complexity of linear The time complexity of binary search ➢ Merge Sort is an efficient, stable sorting algorithm with an average, best-case,
4.
search O(n). O(log n). and worst-case time complexity of O(n log n).
Multidimensional array can be Only single dimensional array is used. 7. What is Linear Search?
5.
used. ➢ The Linear search algorithm works by sequentially iterating through the whole
Linear search performs equality Binary search performs ordering array or list from one end until the target element is found.
6.
comparisons comparisons ➢ If the element is found, it returns its index, else -1.
7. It is less complex. It is more complex.
8. It is very slow process. It is very fast process
C Programming and Data Structures 5.35 5.36 Sorting and Searching Techniques

8. What is binary Search? 14. What is the advantage of using Quick sort algorithm?
➢ Quick sort reduces unnecessary swaps and moves an item to a greater distance,
➢ Binary search follows the divide and conquer approach in which the list is in one move.
divided into two halves, and the item is compared with the middle element of
15. Mention the various types of searching techniques in C.
the list. If the match is found then, the location of the middle element is returned.
➢ Linear search
Otherwise, we search into either of the halves depending upon the result
produced through the match. ➢ Binary search
➢ Binary search can be implemented only on a sorted list of items. If the elements 16. Define Searching.
are not sorted already, we need to sort them first. ➢ Searching in data structure refers to the process of finding the required
9. What is Heap Sort? information from a collection of items stored as elements in the computer
memory.
➢ Heap sort is a comparison-based sorting technique based on Binary Heap data
structure. ➢ These sets of items are in different forms, such as an array, linked list, graph, or
tree.
➢ It is like the selection sort where we first find the minimum element and place
the minimum element at the beginning. Repeat the same process for the 17. Compare Quick sort and Merge Sort.
remaining elements. Basis for comparison Quick Sort Merge Sort
10. What is Time Complexity for Heap Sort? Efficiency Inefficient for larger arrays More efficient
➢ The time complexity for Heap sort in average, best-case, and worst-case Sorting method Internal External
time complexity of O(n log n). Stability Not Stable Stable
11. What is Time Complexity for Insertion Sort? Preferred for for Arrays for Linked Lists
Algorithm Best Case Average Case Worst Case 18. Mention the different ways to select a pivot element.
Insertion Sort O(n) O(n2) O(n2)
o Pick the first element as pivot
12. Why quick sort is preferred for arrays and merge sort for linked lists? o Pick the last element as pivot
➢ Quick sort is an in-place sorting algorithm, i.e. which means it does not require o Pick the Middle element as pivot
any additional space, whereas Merge sort does, which can be rather costly. In o Median-of-three elements
merge sort, the allocation and deallocation of the excess space increase the o Pick three elements, and find the median x of these elements
execution time of the algorithm.
o Use that median as the pivot.
➢ Unlike arrays, in linked lists, we can insert elements in the middle in O(1) extra
o Randomly pick an element as pivot.
space and O(1) time complexities if we are given a reference/pointer to the
previous node. As a result, we can implement the merge operation in the merge 19. What is divide-and-conquer strategy?
sort without using any additional space. ➢ Divide a problem into two or more sub problems
13. In which case insertion sort is used? ➢ Solve the sub problems recursively
➢ Insertion sort has a fast best-case running time and is a good sorting algorithm ➢ Obtain solution to original problem by combining these solutions
to use if the input list is already mostly sorted.
C Programming and Data Structures 5.37

PART B

1. Explain Insertion sort with algorithm and examples.


2. Sort the sequence 13,11,74,37,85,39,22,56,25 using insertion sort.
3. Explain the operation and implementation of merge sort.
4. Write quick sort algorithm and explain with an example.
5. Trace the quick sort algorithm for the following list of numbers.
90,77,60,99,55,88,66
6. Explain linear search algorithm with an example.
7. Explain Binary search algorithm with an example.
8. Write down the merge sort algorithm and give its worst case, best case and average
case analysis.
9. Explain Heap Sort algorithm with an example

You might also like