Algorithm Examples
Learn common algorithms and sorting techniques with these C programming examples.
Bubble Sort
IntermediateImplements bubble sort algorithm to sort an array in ascending order.
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void display(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Original array: ");
display(arr, n);
bubbleSort(arr, n);
printf("Sorted array: ");
display(arr, n);
return 0;
}Linear Search
BeginnerDemonstrates linear search algorithm to find an element in an array.
#include <stdio.h>
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
int main() {
int arr[] = {10, 25, 30, 45, 50, 65, 70};
int n = sizeof(arr)/sizeof(arr[0]);
int target, result;
printf("Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Enter element to search: ");
scanf("%d", &target);
result = linearSearch(arr, n, target);
if (result != -1) {
printf("Element found at index: %d\n", result);
} else {
printf("Element not found\n");
}
return 0;
}Binary Search
IntermediateImplements binary search algorithm for searching in a sorted array.
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 45, 67, 78};
int n = sizeof(arr)/sizeof(arr[0]);
int target, result;
printf("Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Enter element to search: ");
scanf("%d", &target);
result = binarySearch(arr, 0, n-1, target);
if (result != -1) {
printf("Element found at index: %d\n", result);
} else {
printf("Element not found\n");
}
return 0;
}