Searching Techniques
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.
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 main() {
int myArray[] = {4, 7, 2, 1, 9, 5};
int targetValue = 9;
int size = sizeof(myArray) / sizeof(myArray[0]);
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.
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.
Recursive Code
// Binary Search in C
#include <stdio.h>
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>
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.
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
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.
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
for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
{
small = i; //minimum element in unsorted array
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:
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.
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>
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.
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.
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.
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;
}
}
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:
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.
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.
return 0;
}
Output: