SYBCom(CA) DS Practical Slip 19 Q.B

Write a C program to create a string array with at least 5 elements which contains words ending with ‘at’ and ‘an’ sound and sort them using Merge sort.

#include <stdio.h>
#include <string.h>

#define MAX 20
#define SIZE 6

// Function to merge two subarrays
void merge(char arr[][MAX], int left, int mid, int right) {
    int i, j, k;
    int n1 = mid - left + 1;
    int n2 = right - mid;

    char L[n1][MAX], R[n2][MAX];

    // Copy data to temporary arrays
    for (i = 0; i < n1; i++)
        strcpy(L[i], arr[left + i]);
    for (j = 0; j < n2; j++)
        strcpy(R[j], arr[mid + 1 + j]);

    i = 0;
    j = 0;
    k = left;

    // Merge the temp arrays
    while (i < n1 && j < n2) {
        if (strcmp(L[i], R[j]) <= 0) {
            strcpy(arr[k], L[i]);
            i++;
        } else {
            strcpy(arr[k], R[j]);
            j++;
        }
        k++;
    }

    // Copy remaining elements
    while (i < n1) {
        strcpy(arr[k], L[i]);
        i++;
        k++;
    }

    while (j < n2) {
        strcpy(arr[k], R[j]);
        j++;
        k++;
    }
}

// Merge Sort function
void mergeSort(char arr[][MAX], int left, int right) {
    if (left < right) {
        int mid = (left + right) / 2;

        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);

        merge(arr, left, mid, right);
    }
}

int main() {
    // String array with words ending in "at" and "an"
    char words[SIZE][MAX] = {
        "cat",
        "bat",
        "rat",
        "man",
        "fan",
        "can"
    };

    printf("Original Array:\n");
    for (int i = 0; i < SIZE; i++) {
        printf("%s ", words[i]);
    }

    mergeSort(words, 0, SIZE - 1);

    printf("\n\nSorted Array (Ascending Order):\n");
    for (int i = 0; i < SIZE; i++) {
        printf("%s ", words[i]);
    }

    return 0;
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top