Searching and Sorting
Searching and Sorting
C.SAGANA
AP(SrG/CSE)
Difference Between Linear and Binary Search: Linear vs Binary Search
Linear Search
• Also known as Sequential Search used for finding a particular
element within a list
• It sequentially checks each element in the list until a match is found
• It is used for smaller datasets and the data set is unsorted.
linear search algorithm
• Given list: [2, 4, 6, 8, 10]. To find the number 6
1.Start from the first element (2).
2.Compare the current element with the target element (6).
3.If they match, the search ends.
4.If they do not match, move to the next element.
5.Repeat steps 2-4 until the target element is found or the list ends.
#include<stdio.h>
int linearSearch(int arr[], int size, int element){
for (int i = 0; i < size; i++)
{
if(arr[i]==element){
return i;
}
}
return -1;
}
int main(){
// Unsorted array for linear search
int arr[] = {1,3,5,56,4,3,23,5,4,54634,56,34};
int size = sizeof(arr)/sizeof(int);
printf("enter the element to be search");
scanf("%d",&element);
int linear = linearSearch(arr, size, element);
printf("The element %d was found at index %d \n", element, linear);
return 0;
}
Advantage and Disadvantage of Linear
Search
Efficiency: Linear Search can be inefficient for large datasets as it checks each element
Disadvantage
sequentially, leading to a higher time complexity (O(n)) in worst-case scenarios.
Binary Search
• Efficient searching algorithm that finds the position of a target value
within a sorted array.
• It compares the target value to the middle element of the array and
eliminates half of the search space successively.
• It is efficient for large datasets and requires sorted data.
• uses the divide-and-conquer approach
#include<stdio.h> int main(){
int binarySearch(int arr[], int size, int element){
int low, mid, high;
int arr[] =
low = 0; {1,3,5,56,64,73,123,225,444};
high = size-1; int size = sizeof(arr)/sizeof(int);
// Keep searching until low <= high
while(low<=high){ int element;
mid = (low + high)/2; printf("enter the element to be
if(arr[mid] == element){ search");
return mid;
} scanf("%d",&element);
if(arr[mid]<element){ int searchIndex = binarySearch(arr,
low = mid+1;
size, element);
}
else{ printf("The element %d was found at
high = mid -1; index %d \n", element, searchIndex);
}
}
return 0;
return -1; }
}
Advantages and Disadvantages of Binary Search
• Make a one-dimensional array of size ten and fill it with zeros at first.
• Each array slot serves as a bucket for storing elements.