14. Data Structures & AlgorithmsIntermediate12 min read
Searching & Sorting Algorithms in C
Master Linear Search, Binary Search, Bubble Sort, Quick Sort, and the C standard library qsort() with custom comparators.
Key Takeaways & Core Concepts
- Linear Search ($O(N)$) works on unsorted arrays; Binary Search ($O(\log N)$) requires sorted data.
- Quick Sort ($O(N \log N)$ average) is a divide-and-conquer algorithm partitioning around a pivot.
- The C Standard Library provides
qsort(base, num, size, comparator)in<stdlib.h>. - A comparator function returns
< 0ifa < b,0ifa == b, and> 0ifa > b.
Binary Search & qsort() in Action
Let's inspect how to sort arrays efficiently using C's standard qsort() and search with Binary Search:
Sorting and Binary Searching in C
1#include <stdio.h>
2#include <stdlib.h>
3
4// Custom comparator for qsort
5int compareInts(const void *a, const void *b) {
6 int arg1 = *(const int*)a;
7 int arg2 = *(const int*)b;
8 if (arg1 < arg2) return -1;
9 if (arg1 > arg2) return 1;
10 return 0;
11}
12
13int binarySearch(const int arr[], int size, int target) {
14 int left = 0, right = size - 1;
15 while (left <= right) {
16 int mid = left + (right - left) / 2;
17 if (arr[mid] == target) return mid;
18 if (arr[mid] < target) left = mid + 1;
19 else right = mid - 1;
20 }
21 return -1; // Not found
22}
23
24int main(void) {
25 int numbers[] = {64, 25, 12, 22, 11, 90, 45};
26 int size = sizeof(numbers) / sizeof(numbers[0]);
27
28 printf("Original array: ");
29 for (int i = 0; i < size; i++) printf("%d ", numbers[i]);
30 printf("\n");
31
32 // Sort using C standard library qsort
33 qsort(numbers, size, sizeof(int), compareInts);
34
35 printf("Sorted array: ");
36 for (int i = 0; i < size; i++) printf("%d ", numbers[i]);
37 printf("\n");
38
39 // Perform binary search
40 int target = 22;
41 int index = binarySearch(numbers, size, target);
42 printf("Binary search for %d found at sorted index: %d\n", target, index);
43
44 return 0;
45}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
45 lines
Note: qsort takes a generic function pointer comparator with const void* arguments.
Practice & AssessmentC Programming Complete Course
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 1 correct(0 attempted)
1
What must a qsort comparator return if element 'a' should precede element 'b' in ascending order?
Intermediate