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.
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.
#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;
}1 2 3 4 Bubble sort repeatedly swaps out-of-order adjacent pairs until the array is sorted.
#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;
}Found at 3Binary 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.
