Skip to main content
C Programming Basics
CHAPTER 24 Beginner

Searching and Sorting Algorithms

Updated: May 17, 2026
5 min read

# CHAPTER 24

Searching and Sorting Algorithms

1. Introduction

Data is useless if you can't find what you're looking for. Searching is the process of finding an element in a dataset. Sorting is arranging data in a specific order (ascending or descending) to make searching faster. Understanding these algorithms is a core requirement for any software engineering interview.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Implement Linear Search and Binary Search.
  • Understand Time Complexity (Big-O Notation) basics.
  • Implement Bubble Sort, Selection Sort, and Insertion Sort.
  • Decide which algorithm to use based on the dataset.
The simplest method. It checks every element one by one from the beginning to the end.
  • Time Complexity: O(n) (Worst case: element is at the end, requires n checks).
  • Requirement: Works on unsorted arrays.
c
1234567891011121314151617
#include <stdio.h>

int linearSearch(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return i; // Found! Return index
        }
    }
    return -1; // Not found
}

int main() {
    int arr[] = {10, 50, 30, 70, 80, 60, 20, 90, 40};
    int index = linearSearch(arr, 9, 30);
    printf("Found at index: %d\n", index);
    return 0;
}
Much faster, but the array MUST be sorted first. It compares the target to the middle element. If it matches, return. If it's smaller, search the left half. If larger, search the right half.
  • Time Complexity: O(log n) (Extremely fast. Searching 1,000,000 items takes at most 20 checks).
c
12345678910111213
int binarySearch(int arr[], int size, int target) {
    int low = 0;
    int high = size - 1;

    while (low <= high) {
        int mid = low + (high - low) / 2;

        if (arr[mid] == target) return mid;       // Found
        if (arr[mid] < target) low = mid + 1;     // Ignore left half
        else high = mid - 1;                      // Ignore right half
    }
    return -1; // Not found
}

5. Bubble Sort

Repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The largest elements "bubble" to the top.
  • Time Complexity: O(n²) (Very slow for large datasets).
c
12345678910111213
void bubbleSort(int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        // Last i elements are already sorted
        for (int j = 0; j < size - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

6. Selection Sort

Divides the array into a sorted and an unsorted part. Finds the smallest element in the unsorted part and swaps it with the first unsorted element.
  • Time Complexity: O(n²).
c
1234567891011121314
void selectionSort(int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        int min_idx = i;
        for (int j = i + 1; j < size; j++) {
            if (arr[j] < arr[min_idx]) {
                min_idx = j; // Found a new minimum
            }
        }
        // Swap
        int temp = arr[min_idx];
        arr[min_idx] = arr[i];
        arr[i] = temp;
    }
}

7. Insertion Sort

Builds the final sorted array one item at a time, much like sorting a hand of playing cards.
  • Time Complexity: O(n²). Very fast if the array is *almost* sorted (O(n)).
c
12345678910111213
void insertionSort(int arr[], int size) {
    for (int i = 1; i < size; i++) {
        int key = arr[i];
        int j = i - 1;

        // Move elements greater than key one position ahead
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

8. Common Mistakes

  • Using Binary Search on Unsorted Data: Binary Search logic fundamentally relies on order. If the data is unsorted, it will return -1 incorrectly.
  • Bubble Sort j loop limit: The inner loop should go to size - i - 1. If it goes to size - 1, it will check arr[j+1] which might be out of bounds!
  • Swapping logic: A proper swap requires a temporary variable (temp). Doing a = b; b = a; makes them both identical.

9. Exercises

  1. 1. Modify Bubble Sort to include a boolean swapped flag. If a full pass happens without any swaps, break the loop early (Optimized Bubble Sort).
  1. 2. Trace Insertion Sort on paper for the array: {12, 11, 13, 5, 6}.

10. MCQ Quiz with Answers

Question 1

Which search algorithm requires the array to be sorted?

Question 2

What is the worst-case time complexity of Linear Search?

Question 3

Which sorting algorithm simulates sorting playing cards in your hand?

Question 4

What is the worst-case time complexity of Bubble Sort?

Question 5

Binary Search time complexity is:

Question 6

Selection Sort finds the ________ element in the unsorted portion and swaps it.

Question 7

If an array has 100 elements, in the worst case, how many comparisons does Linear Search make?

Question 8

For the same 100 elements, roughly how many comparisons does Binary Search make?

Question 9

Bubble sort pushes the _______ element to the end of the array in each outer loop pass.

Question 10

Why is a temporary variable needed when swapping two array elements?

11. Interview Questions

  • Q: Explain why Binary Search is O(log n) time complexity.
  • Q: When would Insertion Sort be a better choice than Bubble Sort or Selection Sort?
  • Q: Explain the swapping bug a = b; b = a; and how to fix it using a temporary variable or XOR bitwise logic.

12. Summary

Linear search checks every element, while Binary search cuts sorted data in half repeatedly. Bubble, Selection, and Insertion sorts are simple O(n²) sorting algorithms. While not used in high-performance production code (where O(n log n) algorithms like QuickSort or MergeSort are preferred), they form the foundation of algorithmic thinking.

13. Next Chapter Recommendation

In Chapter 25: Bitwise Programming, we will explore how C manipulates data at the lowest possible level: the binary bits (1s and 0s).

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·