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

Searching Techniques

Uploaded by

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

Searching Techniques

Uploaded by

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

Searching techniques

Searching is the process of finding some particular element in the list. If the
element is present in the list, then the process is called successful, and the
process returns the location of that element; otherwise, the search is called
unsuccessful.

Linear search is also called as sequential search algorithm. It is the simplest


searching algorithm. 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. If the
match is found, then the location of the item is returned; otherwise, the algorithm
returns NULL.

It is widely used to search an element from the unordered list, i.e., the list in which
items are not sorted.
1. Linear_Search(a, n, val) // 'a' is the given array, 'n' is the size of given array, 'val' is
the value to search
2. Step 1: set pos = -1
3. Step 2: set i = 1
4. Step 3: repeat step 4 while i <= n
5. Step 4: if a[i] == val
6. set pos = i
7. print pos
8. go to step 6
9. [end of if]
10. set ii = i + 1
11. [end of loop]
12. Step 5: if pos = -1
13. print "value is not present in the array "
14. [end of if]
15. Step 6: exit
LINEAR SEARCH PROGRAM
#include <stdio.h>

int linearSearch(int arr[], int size, int target) {


for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return the index of the element
}
}
return -1; // If the target is not found, return -1
}

int main() {
int myArray[] = {4, 7, 2, 1, 9, 5};
int targetValue = 9;
int size = sizeof(myArray) / sizeof(myArray[0]);

int result = linearSearch(myArray, size, targetValue);


if (result != -1) {
printf("The target value %d is found at index %d.\n", targetValue, result);
} else {
printf("The target value is not present in the array.\n");
}

return 0;
}

Output:
The target value 9 is found at index 4.

BINARY SEARCH

Searching is the process of finding some particular element in the list. If the
element is present in the list, then the process is called successful, and the
process returns the location of that element. Otherwise, the search is called
unsuccessful.

Linear Search and Binary Search are the two popular searching techniques. Here
we will discuss the Binary Search Algorithm.

Binary search is the search technique that works efficiently on sorted lists. Hence,
to search an element into some list using the binary search technique, we must
ensure that the list is sorted.

Binary search follows the divide and conquer approach in which the list is divided
into two halves, and the item is compared with the middle element of the list. If
the match is found then, the location of the middle element is returned.
Otherwise, we search into either of the halves depending upon the result
produced through the match.

Now, let's see the algorithm of Binary Search.


Algorithm
1. Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array, 'lower_b
ound' is the index of the first array element, 'upper_bound' is the index of the last
array element, 'val' is the value to search
2. Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
3. Step 2: repeat steps 3 and 4 while beg <=end
4. Step 3: set mid = (beg + end)/2
5. Step 4: if a[mid] = val
6. set pos = mid
7. print pos
8. go to step 6
9. else if a[mid] > val
10. set end = mid - 1
11. else
12. set beg = mid + 1
13. [end of if]
14. [end of loop]
15. Step 5: if pos = -1
16. print "value is not present in the array"
17. [end of if]
18. Step 6: exit

Working of Binary search


Now, let's see the working of the Binary Search Algorithm.

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.

There are two methods to implement the binary search algorithm -


o Iterative method
o Recursive method

Recursive Code
// Binary Search in C

#include <stdio.h>

int binarySearch(int array[], int x, int low, int high) {


if (high >= low) {
int mid = low + (high - low) / 2;

// If found at mid, then return it


if (array[mid] == x)
return mid;

// Search the left half


if (array[mid] > x)
return binarySearch(array, x, low, mid - 1);

// Search the right half


return binarySearch(array, x, mid + 1, high);
}

return -1;
}

int main(void) {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int n = sizeof(array) / sizeof(array[0]);
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
}

Output:
Element is found at index 1

Explanation:
o The binarySearch function takes an array, the element to search for (x), the
lower index (low), and the higher index (high) as parameters.
o It first checks if high is greater than or equal to low. If not, it means the
element was not found, and it returns -1.
o If high is greater than or equal to low, it calculates the middle index mid
using the formula low + (high - low) / 2.
o It then checks if the element at the middle index (array[mid]) is equal to x.
If they are equal, it means the element is found, and it returns the index
mid.
o If array[mid] is greater than x, it means the element lies in the left half of
the array. In this case, the binarySearch function is called recursively with
low unchanged and high set to mid - 1.
o If array[mid] is less than x, it means the element lies in the right half of the
array. In this case, the binarySearch function is called recursively with low
set to mid + 1 and high unchanged.
o If the element is not found after the recursive calls, the function returns -1.
o In the main function, an array {3, 4, 5, 6, 7, 8, 9} is defined, and the size of
the array n is calculated using the formula sizeof(array) / sizeof(array[0]).
o The element x to search for is set to 4.
o The binarySearch function is called with the array, x, and the range of
indices 0 to n - 1.
o The returned result is stored in the result variable.
o Finally, the result is checked. If it is -1, it means the element was not found,
and "Not found" is printed. Otherwise, the index where the element was
found is printed as "Element is found at index result"

Iterative
#include <stdio.h>

int binarySearch(int array[], int x, int low, int high) {


// Repeat until the pointers low and high meet each other
while (low <= high) {
int mid = low + (high - low) / 2;

if (array[mid] == x)
return mid;

if (array[mid] < x)
low = mid + 1;

else
high = mid - 1;
}

return -1;
}

int main(void) {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int n = sizeof(array) / sizeof(array[0]);
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
return 0;
}

Output:
Element is found at index 1

Explanation:
o The binarySearch function takes an array, the element to search for (x), the
lower index (low), and the higher index (high) as parameters.
o It uses a while loop that continues until the low pointer is less than or
equal to the high pointer.
o Inside the loop, it calculates the middle index mid using the formula low +
(high - low) / 2.
o It then checks if the element at the middle index (array[mid]) is equal to x.
If they are equal, it means the element is found, and it returns the index
mid.
o If array[mid] is less than x, it means the element lies in the right half of the
array. In this case, the low pointer is updated to mid + 1.
o If array[mid] is greater than x, it means the element lies in the left half of
the array. In this case, the high pointer is updated to mid - 1.
o If the element is not found after the loop, it means the element is not
present in the array, and the function returns -1.
o In the main function, an array {3, 4, 5, 6, 7, 8, 9} is defined, and the size of
the array n is calculated using the formula sizeof(array) / sizeof(array[0]).
o The element x to search for is set to 4.
o The binarySearch function is called with the array, x, and the range of
indices 0 to n - 1.
o The returned result is stored in the result variable.
o Finally, the result is checked. If it is -1, it means the element was not found,
and "Not found" is printed. Otherwise, the index where the element was
found is printed as "Element is found at index result".
Sorting Algorithms
Sorting is the process of arranging the elements of an array so that they can be
placed either in ascending or descending order.

For example, consider an array A = {A1, A2, A3, A4, ?? An }, the array is called to
be in ascending order if element of A are arranged like A1 > A2 > A3 > A4 > A5
> ? > An .

Bubble sort
Bubble sort works on the repeatedly swapping of adjacent elements until they are
not in the intended order. It is called bubble sort because the movement of array
elements is just like the movement of air bubbles in the water. Bubbles in water
rise up to the surface; similarly, the array elements in bubble sort move to the end
in each iteration.

Although it is simple to use, it is primarily used as an educational tool because


the performance of bubble sort is poor in the real world. It is not suitable for
large data sets.

In the algorithm given below, suppose arr is an array of n elements. The


assumed swap function in the algorithm will swap the values of given array
elements.

algorithm
begin BubbleSort(arr)
for all array elements
if arr[i] > arr[i+1]
swap(arr[i], arr[i+1])
end if
end for
return arr
end BubbleSort

Program: Write a program to implement bubble sort in C language.


#include<stdio.h>
void print(int a[], int n) //function to print array elements
{
int i;
for(i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
}
void bubble(int a[], int n) // function to implement bubble sort
{
int i, j, temp;
for(i = 0; i < n; i++)
{
for(j = i+1; j < n; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
void main ()
{
int i, j,temp;
int a[5] = { 10, 35, 32, 13, 26};
int n = sizeof(a)/sizeof(a[0]);
printf("Before sorting array elements are - \n");
print(a, n);
bubble(a, n);
printf("\nAfter sorting array elements are - \n");
print(a, n);
}

Output
Selection Sort
In selection sort, the smallest value among the unsorted elements of the array is
selected in every pass and inserted to its appropriate position into the array. It is
also the simplest algorithm. It is an in-place comparison sorting algorithm. In this
algorithm, the array is divided into two parts, first is sorted part, and another one
is the unsorted part. Initially, the sorted part of the array is empty, and unsorted
part is the given array. Sorted part is placed at the left, while the unsorted part is
placed at the right.

In selection sort, the first smallest element is selected from the unsorted array and
placed at the first position. After that second smallest element is selected and
placed in the second position. The process continues until the array is entirely
sorted.

Selection sort is generally used when -


o A small array is to be sorted
o Swapping cost doesn't matter
o It is compulsory to check all elements

Now, let's see the algorithm of selection sort.

Algorithm
1. SELECTION SORT(arr, n)
2.
3. Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
4. Step 2: CALL SMALLEST(arr, i, n, pos)
5. Step 3: SWAP arr[i] with arr[pos]
6. [END OF LOOP]
7. Step 4: EXIT
8.
9. SMALLEST (arr, i, n, pos)
10. Step 1: [INITIALIZE] SET SMALL = arr[i]
11. Step 2: [INITIALIZE] SET pos = i
12. Step 3: Repeat for j = i+1 to n
13. if (SMALL > arr[j])
14. SET SMALL = arr[j]
15. SET pos = j
16. [END OF if]
17. [END OF LOOP]
18. Step 4: RETURN pos

Program: Write a program to implement selection sort in C language.


#include <stdio.h>

void selection(int arr[], int n)


{
int i, j, small;

for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
{
small = i; //minimum element in unsorted array

for (j = i+1; j < n; j++)


if (arr[j] < arr[small])
small = j;
// Swap the minimum element with the first element
int temp = arr[small];
arr[small] = arr[i];
arr[i] = temp;
}
}

void printArr(int a[], int n) /* function to print the array */


{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
selection(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}
Output:

After the execution of above code, the output will be -

Merge sort is similar to the quick sort algorithm as it uses the divide and conquer
approach to sort the elements. It is one of the most popular and efficient sorting
algorithm. It divides the given list into two equal halves, calls itself for the two
halves and then merges the two sorted halves. We have to define
the merge() function to perform the merging.

The sub-lists are divided again and again into halves until the list cannot be
divided further. Then we combine the pair of one element lists into two-element
lists, sorting them in the process. The sorted two-element pairs is merged into the
four-element lists, and so on until we get the sorted list.

Now, let's see the algorithm of merge sort.

Algorithm
In the following algorithm, arr is the given array, beg is the starting element,
and end is the last element of the array.
1. MERGE_SORT(arr, beg, end)
2.
3. if beg < end
4. set mid = (beg + end)/2
5. MERGE_SORT(arr, beg, mid)
6. MERGE_SORT(arr, mid + 1, end)
7. MERGE (arr, beg, mid, end)
8. end of if
9.
10. END MERGE_SORT

The important part of the merge sort is the MERGE function. This function
performs the merging of two sorted sub-arrays that are A[beg…
mid] and A[mid+1…end], to build one sorted array A[beg…end]. So, the inputs
of the MERGE function are A[], beg, mid, and end.
Program: Write a program to implement merge sort in C language.
#include <stdio.h>

/* Function to merge the subarrays of a[] */


void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;
int LeftArray[n1], RightArray[n2]; //temporary arrays

/* copy data to temp arrays */


for (int i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];

i = 0; /* initial index of first sub-array */


j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */

while (i < n1 && j < n2)


{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}
while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}

void mergeSort(int a[], int beg, int end)


{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}

/* Function to print the array */


void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17, 40, 42 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArray(a, n);
mergeSort(a, 0, n - 1);
printf("After sorting array elements are - \n");
printArray(a, n);
return 0;
}
Output:

Insertion Sort
Insertion sort works similar to the sorting of playing cards in hands. It is assumed
that the first card is already sorted in the card game, and then we select an
unsorted card. If the selected unsorted card is greater than the first card, it will be
placed at the right side; otherwise, it will be placed at the left side. Similarly, all
unsorted cards are taken and put in their exact place.

The same approach is applied in insertion sort. The idea behind the insertion sort
is that first take one element, iterate it through the sorted array.

insertion sort has various advantages such as –


o Simple implementation
o Efficient for small data sets
o Adaptive, i.e., it is appropriate for data sets that are already substantially
sorted.

Now, let's see the algorithm of insertion sort.

Algorithm
The simple steps of achieving the insertion sort are listed as follows -

Step 1 - If the element is the first element, assume that it is already sorted. Return
1.

Step2 - Pick the next element, and store it separately in a key.

Step3 - Now, compare the key with all elements in the sorted array.

Step 4 - If the element in the sorted array is smaller than the current element,
then move to the next element. Else, shift greater elements in the array towards
the right.

Step 5 - Insert the value.

Step 6 - Repeat until the array is sorted.


Program: Write a program to implement insertion sort in C language.
#include <stdio.h>

void insert(int a[], int n) /* function to sort an aay with insertion sort */
{
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;

while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one
position ahead from their current position*/
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}

void printArr(int a[], int n) /* function to print the array */


{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);

return 0;
}
Output:

Sorting is a way of arranging items in a systematic manner. Quicksort is the widely


used sorting algorithm that makes n log n comparisons in average case for
sorting an array of n elements. It is a faster and highly efficient sorting algorithm.
This algorithm follows the divide and conquer approach. Divide and conquer is a
technique of breaking down the algorithms into subproblems, then solving the
subproblems, and combining the results back together to solve the original
problem.

Divide: In Divide, first pick a pivot element. After that, partition or rearrange the
array into two sub-arrays such that each element in the left sub-array is less than
or equal to the pivot element and each element in the right sub-array is larger
than the pivot element.

Conquer: Recursively, sort two subarrays with Quicksort.

Combine: Combine the already sorted array.

Quicksort picks an element as pivot, and then it partitions the given array around
the picked pivot element. In quick sort, a large array is divided into two arrays in
which one holds values that are smaller than the specified value (Pivot), and
another array holds the values that are greater than the pivot.

After that, left and right sub-arrays are also partitioned using the same approach.
It will continue until the single element remains in the sub-array.

Choosing the pivot


Picking a good pivot is necessary for the fast implementation of quicksort.
However, it is typical to determine a good pivot. Some of the ways of choosing a
pivot are as follows -
o Pivot can be random, i.e. select the random pivot from the given array.
o Pivot can either be the rightmost element of the leftmost element of the
given array.
o Select median as the pivot element.
Algorithm
Algorithm:
QUICKSORT (array A, start, end)
{
if (start < end)
{
p = partition(A, start, end)
QUICKSORT (A, start, p - 1)
QUICKSORT (A, p + 1, end)
}
}

Program: Write a program to implement quicksort in C language.


#include <stdio.h>
/* function that consider last element as pivot,
place the pivot at its exact position, and place
smaller elements to left of pivot and greater
elements to right of pivot. */
int partition (int a[], int start, int end)
{
int pivot = a[end]; // pivot element
int i = (start - 1);

for (int j = start; j <= end - 1; j++)


{
// If current element is smaller than the pivot
if (a[j] < pivot)
{
i++; // increment index of smaller element
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int t = a[i+1];
a[i+1] = a[end];
a[end] = t;
return (i + 1);
}
/* function to implement quick sort */
void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting index,
end = Ending index */
{
if (start < end)
{
int p = partition(a, start, end); //p is the partitioning index
quick(a, start, p - 1);
quick(a, p + 1, end);
}
}

/* function to print an array */


void printArr(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{
int a[] = { 24, 9, 29, 14, 19, 27 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
quick(a, 0, n - 1);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);

return 0;
}

Output:

You might also like