Essential C Algorithms and Data Structures Implementation

Linear Search Implementation

#include <stdio.h>
#include <time.h>

int linearSearch(int arr[], int n, int key) {
    for(int i = 0; i < n; i++) {
        if(arr[i] == key) return i;
    }
    return -1;
}

int main() {
    int arr[10000], n, key, pos;
    clock_t start, end;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter elements:\n");
    for(int i = 0; i < n; i++) scanf("%d", &arr[i]);
    printf("Enter element to search: ");
    scanf("%d", &key);
    start = clock();
    pos = linearSearch(arr, n, key);
    end = clock();
    if(pos == -1) printf("Element not found\n");
    else printf("Element found at position %d\n", pos + 1);
    printf("Time taken = %f seconds\n", ((double)(end - start)) / CLOCKS_PER_SEC);
    return 0;
}

Binary Search Implementation

#include <stdio.h>
#include <time.h>

int binarySearch(int arr[], int n, int key) {
    int low = 0, high = n - 1;
    while (low <= high) {
        int mid = (low + high) / 2;
        if (arr[mid] == key) return mid;
        else if (arr[mid] < key) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

Tower of Hanoi

#include <stdio.h>

void towerOfHanoi(int n, char source, char auxiliary, char destination) {
    if (n == 1) {
        printf("Move disk 1 from %c to %c\n", source, destination);
        return;
    }
    towerOfHanoi(n - 1, source, destination, auxiliary);
    printf("Move disk %d from %c to %c\n", n, source, destination);
    towerOfHanoi(n - 1, auxiliary, source, destination);
}

Min-Max Algorithm

#include <stdio.h>

struct Pair { int min; int max; };
struct Pair minMax(int arr[], int low, int high) {
    struct Pair result, left, right;
    if (low == high) { result.min = result.max = arr[low]; return result; }
    if (high == low + 1) {
        result.max = (arr[low] > arr[high]) ? arr[low] : arr[high];
        result.min = (arr[low] < arr[high]) ? arr[low] : arr[high];
        return result;
    }
    int mid = (low + high) / 2;
    left = minMax(arr, low, mid);
    right = minMax(arr, mid + 1, high);
    result.min = (left.min < right.min) ? left.min : right.min;
    result.max = (left.max > right.max) ? left.max : right.max;
    return result;
}

Prim’s Algorithm

#include <stdio.h>
#define MAX 20
#define INF 999
// Prim's logic for Minimum Spanning Tree

Kruskal’s Algorithm

#include <stdio.h>
#define MAX 20
// Kruskal's logic for Minimum Spanning Tree