0% found this document useful (0 votes)
11 views

8 Searching and Sorting

The document discusses linear search and binary search algorithms for searching an array for a key value. It also discusses bubble sort algorithm for sorting an array of values in ascending order. Linear search compares each element to find a match while binary search recursively divides the array and searches halves. Bubble sort repeatedly compares adjacent elements and swaps them if out of order until sorted.

Uploaded by

narasimhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

8 Searching and Sorting

The document discusses linear search and binary search algorithms for searching an array for a key value. It also discusses bubble sort algorithm for sorting an array of values in ascending order. Linear search compares each element to find a match while binary search recursively divides the array and searches halves. Bubble sort repeatedly compares adjacent elements and swaps them if out of order until sorted.

Uploaded by

narasimhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

EST102 : Programming in C

Chapter 8
Searching and sorting

Narasimhan T.

8.1 Searching
Given an array A and a value called key, the problem of searching is to determine if the key
is present in A or not. If the key is present, the positions are also printed. Two prominent
approaches to searching are linear search and binary search whose discussions are in order
now.

8.1.1 Linear search


Linear search is also referred to as sequential search and the underlying idea is very simple:
Starting from the zeroth element, compare every array element with the key to be searched.
If there is no match, continue the search with the next element. If there is a match, display
the index (position) and move to next element for comparison. This process is repeated
until you reach the end of the array.

Example 8.1. Let the array A be ⟨5, 0, 3, -2, 7, 6, 3⟩ and key be 3. The working
of linear search algorithm on this input is shown in Table 8.1. The final output is 2 6. ■

The program for linear search follows now.


Program 8.63. Linear search

#include<stdio.h>
main()
{
int a[10],i,n,key,flag=0;
printf("Enter the array size\n");
scanf("%d",&n);

119
120 CHAPTER 8. SEARCHING AND SORTING

Table 8.1: Illustration of linear search algorithm

i A[i] Remarks Action


0 5 A[i] ̸= key Move on
1 0 A[i] ̸= key Move on
2 3 A[i] == key Print the position and move on
3 -2 A[i] ̸= key Move on
4 7 A[i] ̸= key Move on
5 6 A[i] ̸= key Move on
6 3 A[i] == key Print the position and stop

printf("Enter the elements\n");


for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(a[i]==key)
{
flag=1;
printf("Key %d found at index %d\n",key,i);
}
}
if(flag==0)
printf("Sorry, the key %d is not present in the array\n",key);
}

8.1.2 Binary search


If the elements in the array A are sorted, then there is a much more efficient algorithm than
linear search. This algorithm is known as binary search. Its logic is this: Let low, mid and
high denote the first, middle and last positions in the array respectively. To search for a
key in the array A, you compare it with the middle element A[mid]. If it matches, then the
search is successful and it is terminated after printing mid. If there is no match, the array
is divided into two halves (known as sub arrays). The left subarray consists of the array
elements to the left of A[mid] and the right subarray consists of the array elements to the
right of A[mid]. To be more specific, the contents of the two sub srrays are:

Left subarray - ⟨A[low], A[low + 1], · · · · · · A[mid − 1]⟩


8.1. SEARCHING 121

Right subarray - ⟨A[mid + 1], A[mid + 2], · · · · · · A[high]⟩


Since the array is sorted, it is obvious that all elements in left sub array will be less than
A[mid] and all elements in the right subarray will be greater than A[mid]. Thus, if key >
A[mid], then key cannot be in the left subarray and hence searching is to be done only in
the right subarray. This is achieved by setting low = mid + 1 (existing value of high is
kept unchanged). Otherwise, you need to search only in the left subarray by setting high
= mid - 1 (existing value of low is kept unchanged).
Searching in the sub array works exactly same as before: you compare key with the
middle element (of the subarray) and divide the subarray into two halves if key is not equal
to the middle element. Then searching is continued in the left or right half of the subarray
as the case maybe. This process is repeated until either the required element is found or
the division into two halves gives a single element.
Example 8.2. Let the array A be ⟨-2, 0, 3, 6, 7, 12, 28, 45, 57, 92⟩ and key be
28. The working of binary search algorithm on this input is shown in Table 8.2. The final
output is 6. ■

Table 8.2: Illustration of binary search algorithm

low mid high Remarks Action


0 4 9 key > A[mid] Continue search in right subarray
5 7 9 key < A[mid] Continue search in left subarray
5 5 6 key > A[mid] Continue search in right subarray
6 6 6 key == A[mid] Print mid and stop

The program for binary search algorithm is given below.


Program 8.64. Binary search

#include<stdio.h>
main()
{
int a[10],i,n,key,low,high,mid,flag=0;
printf("Enter the array size\n");
scanf("%d",&n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
122 CHAPTER 8. SEARCHING AND SORTING

{
mid=(low+high)/2;
if(a[mid]==key)
{
flag=1;
printf("Key found at index %d\n",mid);
break;
}
else if(key>a[mid])
low=mid+1; //Search in right half
else
high=mid-1; // Search in left half
}
if(flag==0)
printf("Sorry, the key %d is not present in the array\n",key);
}

8.2 Sorting
Sorting means arranging the elements of an array in an order. The order could be ascending
or descending. Unless otherwise specified, ascending order is the norm. There are a good
number of sorting algorithms. The most common one is the bubble sort which is discussed
here.

8.2.1 Bubble sort


The algorithm starts by comparing each element in the array with its adjacent element,
and then swaps them if they are out of order. In this way, when all the elements are
considered once, the largest element will move to its correct position. Then, the remaining
elements (without the largest element) are considered pairwise and swapped if required.
The algorithm repeats this process multiple number of times (passes) until all the elements
settle down in their corresponding positions. During every pass, the largest among the
values considered then, bubbles (moves) through the array and settles down. This justifies
the name bubble sort for this sorting algorithm.

Example 8.3. Suppose you want to sort the numbers ⟨5, 1, 4, 7, 2, 6⟩. You consider the
elements in pair and swap them if necessary. The various passes are shown in Figure 8.1.
The pair of elements which are under current consideration are underlined. In pass 0, the
largest element 7 moves to its correct position. This is indicated by showing 7 in a box.
In pass 1, the next largest element 6 settles down. Thus, now 6 and 7 are in their correct
positions shown by putting them in a box. This is continued until you end up with a single
element, which is by default sorted. Finally the sorted list is output. ■
8.2. SORTING 123

Input
5 1 4 7 2 6

Pass 0
5 1 4 7 2 6 (swap)
1 5 4 7 2 6 (swap)
1 4 5 7 2 6
1 4 5 7 2 6 (swap)
1 4 5 2 7 6 (swap)
1 4 5 2 6 7

Pass 1
1 4 5 2 6 7
1 4 5 2 6 7
1 4 5 2 6 7 (swap)
1 4 2 5 6 7
1 4 2 5 6 7

Pass 2
1 4 2 5 6 7
1 4 2 5 6 7 (swap)
1 2 4 5 6 7
1 2 4 5 6 7

Pass 3
1 2 4 5 6 7
1 2 4 5 6 7
1 2 4 5 6 7

Pass 4
1 2 4 5 6 7
1 2 4 5 6 7

Output
1 2 4 5 6 7

Figure 8.1: Illustration of bubble sort

From Example 8.3, the following points are clear:

• To sort n elements n − 1 passes (pass 0 through pass n − 2) are required.


124 CHAPTER 8. SEARCHING AND SORTING

• In pass 0, n − 1 elements are compared with their adjacent elements in pair (Note
that the last element has no adjacent neighbour) and swapped if necessary. In pass
1, you compare n − 2 elements with their neighbours. Thus in pass i, you need to
consider only n − (i + 1) or n − i − 1 elements.

These points immediately take you to the following implementation.


Program 8.65. Bubble sort

#include<stdio.h>
main()
{
int a[10],i,j,n,temp;
printf("Array size please\n");
scanf("%d",&n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Array elements in ascending order:\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);

8.2.2 Sorting strings


Bubble sort can be applied to a collection of strings as well. But you need to be mindful of
some points:

• While considering strings pairwise, the swapping is to be done only when the second
string of the pair alphabetically precedes the first. This check is to be accomplished
using strcmp() function.

• The temp variable used in the swapping process should also be a string.
8.2. SORTING 125

• Since one string cannot be assigned to another, strcpy() is to be used while swapping.

Following is the bubble sort logic to sort a table of strings.


Program 8.66. Bubble sort for strings

#include<stdio.h>
#include<string.h>
main()
{
char strs[10][10],temp[10];
int i,j,n;
printf("How many strings do you want to sort?\n");
scanf("%d",&n);
printf("Enter the strings\n");
for(i=0;i<n;i++)
scanf("%s",strs[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(strcmp(strs[j],strs[j+1])>0)
{
strcpy(temp,strs[j]);
strcpy(strs[j],strs[j+1]);
strcpy(strs[j+1],temp);
}
}
}
printf("Strings in ascending order:\n");
for(i=0;i<n;i++)
printf("%s\n",strs[i]);

You might also like