Searching and SortingAlgorithms
in C
Linear Search, Binary Search,
Insertion Sort, and Bubble Sort
For B.Tech Students, IIT (BHU)
2.
Linear Search -Introduction
• Linear search scans each element in a list
sequentially until the target element is found.
• Works on both sorted and unsorted lists.
• Simple but inefficient for large datasets.
3.
Linear Search -Flowchart
• Start → Input array & key → For each element
→ If element == key → Print Found → Stop →
Else continue → End
4.
Linear Search -C Program
• #include <stdio.h>
• int main() {
• int arr[5] = {10, 20, 30, 40, 50};
• int key = 30, i, found = 0;
• for(i=0; i<5; i++) {
• if(arr[i] == key) {
• printf("Element found at index %d", i);
• found = 1;
• break;
• }
• }
• if(!found) printf("Element not found");
• return 0;
• }
5.
Linear Search -Complexity
• Best Case: O(1)
• Worst Case: O(n)
• Average Case: O(n)
• Space Complexity: O(1)
6.
Binary Search -Introduction
• Works on sorted arrays only.
• Repeatedly divides the search interval in half.
• More efficient than linear search.
7.
Binary Search -Flowchart
• Start → Set low=0, high=n-1 →
while(low<=high): mid=(low+high)/2 → If
arr[mid]==key → Found → Else adjust
low/high → End
8.
Binary Search -C Program
• #include <stdio.h>
• int main() {
• int arr[] = {10, 20, 30, 40, 50};
• int low = 0, high = 4, key = 30, mid;
• while(low <= high) {
• mid = (low + high) / 2;
• if(arr[mid] == key) {
• printf("Element found at index %d", mid);
• return 0;
• } else if(arr[mid] < key)
• low = mid + 1;
• else
• high = mid - 1;
• }
• printf("Element not found");
• return 0;
9.
Binary Search -Complexity
• Best Case: O(1)
• Worst Case: O(log n)
• Average Case: O(log n)
• Space Complexity: O(1)
10.
Insertion Sort -Introduction
• Builds the sorted array one item at a time.
• Good for small datasets.
• Works similar to sorting playing cards in hand.
11.
Insertion Sort -Flowchart
• Start → Loop from 1 to n → Pick key = arr[i] →
Compare with left side → Shift elements →
Insert key → Repeat → End
Bubble Sort -Complexity
• Best Case: O(n)
• Worst Case: O(n²)
• Average Case: O(n²)
• Space Complexity: O(1)
18.
Comparison of Algorithms
•Linear Search: O(n)
• Binary Search: O(log n)
• Insertion Sort: O(n²)
• Bubble Sort: O(n²)
• Binary Search is faster for large sorted data.
• Insertion Sort often outperforms Bubble Sort
for small datasets.
19.
Summary
• Searching andsorting are core algorithmic
operations.
• Linear and Binary Search differ in efficiency
and precondition (sorted data).
• Insertion and Bubble Sort are simple but not
efficient for large datasets.
• Useful for understanding basic algorithm
design and complexity.