Posts

Showing posts from September, 2024

Quick Sort

#include <stdio.h> void swap(int*, int*); int partition(int[], int, int); void quicksort(int[], int, int); void swap(int *p, int *q) {     int temp = *p;     *p = *q;     *q = temp; } int partition(int a[], int l, int h) {     int pivot = a[l];     int i = l - 1;     int j = h + 1;     while (1) {         do {             i++;         } while (a[i] < pivot);         do {             j--;         } while (a[j] > pivot);         if (i >= j)             return j;         swap(&a[i], &a[j]);     } } void quicksort(int a[], int l, int h) {     if (l < h) {         int s = partition(a, l, h);         quicksort(a, l, s);    ...

Merge Sort

#include <stdio.h> void merge(int arr[], int left, int mid, int right) {     int i, j, k;     int n1 = mid - left + 1;     int n2 = right - mid;     int L[n1], R[n2];     for (i = 0; i < n1; i++)         L[i] = arr[left + i];     for (j = 0; j < n2; j++)         R[j] = arr[mid + 1 + j];     i = 0;     j = 0;     k = left;     while (i < n1 && j < n2) {         if (L[i] <= R[j]) {             arr[k] = L[i];             i++;         } else {             arr[k] = R[j];             j++;         }         k++;     }     while (i < n1) {         arr[k] = L[i];         ...

AVL Trees

#include <stdio.h> #include <stdlib.h> // Structure to represent a node in the AVL tree struct Node {     int key;     struct Node* left;     struct Node* right;     int height; }; // Function to get the height of the node int height(struct Node* N) {     if (N == NULL)         return 0;     return N->height; } // Function to get the maximum of two integers int max(int a, int b) {     return (a > b) ? a : b; } // Helper function that allocates a new node with the given key struct Node* newNode(int key) {     struct Node* node = (struct Node*)malloc(sizeof(struct Node));     node->key = key;     node->left = NULL;     node->right = NULL;     node->height = 1; // New node is initially added at leaf     return(node); } // Right rotate subtree rooted with y struct Node* rightRotate(struct Node* y) {     ...