C ยท Chapter 43 of 45

C Sorting and Searching

Sorting arranges data in a particular order (like ascending), while searching finds whether and where a value exists in a collection. Both are fundamental operations used constantly in real programs.

Bubble sort is a simple (though slow) sorting algorithm good for learning, while binary search is a fast searching algorithm that requires the data to already be sorted.

Syntax
for (i...) for (j...) if (arr[j] > arr[j+1]) swap;
while (low <= high) { mid = ...; }

Bubble sort

Bubble sort repeatedly compares adjacent elements and swaps them if they're out of order, 'bubbling' the largest values to the end after each full pass through the array.

Binary search

Binary search repeatedly halves the search range by comparing the target to the middle element, only working correctly on data that is already sorted. It's much faster than checking every element (linear search) for large datasets.

Example 1 (c)
#include <stdio.h>

int main() {
  int arr[4] = {4, 2, 3, 1};
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3 - i; j++) {
      if (arr[j] > arr[j+1]) {
        int temp = arr[j];
        arr[j] = arr[j+1];
        arr[j+1] = temp;
      }
    }
  }
  for (int i = 0; i < 4; i++) printf("%d ", arr[i]);
  printf("\n");
  return 0;
}
Output
1 2 3 4 

Bubble sort repeatedly swaps out-of-order adjacent pairs until the array is sorted.

Example 2 (c)
#include <stdio.h>

int main() {
  int arr[5] = {1, 3, 5, 7, 9};
  int target = 7, low = 0, high = 4;
  while (low <= high) {
    int mid = (low + high) / 2;
    if (arr[mid] == target) { printf("Found at %d\n", mid); break; }
    else if (arr[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return 0;
}
Output
Found at 3

Binary search narrows the range in half each step until it finds the target.

Key points

  • Bubble sort repeatedly swaps adjacent out-of-order elements.
  • Binary search requires the data to already be sorted.
  • Binary search is much faster than linear search on large sorted data.
  • Sorting algorithms differ in speed; more efficient ones (like quicksort) exist beyond bubble sort.
๐Ÿ’ก Note: Bubble sort is simple to understand but inefficient for large datasets; it's mainly used for teaching purposes.

๐Ÿ“ Quick Quiz

1. What does bubble sort repeatedly do?

2. What is required before using binary search?

3. Why is binary search generally faster than linear search?