Write a C Program to implement Merge Sort

 #include <stdio.h>

#include <stdlib.h>


// Function to merge two subarrays

void merge(int arr[], int left, int mid, int right) {

    int n1 = mid - left + 1;

    int n2 = right - mid;


    // Create temporary arrays

    int L[n1], R[n2];


    // Copy data to temporary arrays L[] and R[]

    for (int i = 0; i < n1; i++)

        L[i] = arr[left + i];

    for (int j = 0; j < n2; j++)

        R[j] = arr[mid + 1 + j];


    // Merge the temporary arrays back into arr[left..right]

    int i = 0; // Initial index of first subarray

    int j = 0; // Initial index of second subarray

    int k = left; // Initial index of merged subarray

    while (i < n1 && j < n2) {

        if (L[i] <= R[j]) {

            arr[k] = L[i];

            i++;

        } else {

            arr[k] = R[j];

            j++;

        }

        k++;

    }


    // Copy the remaining elements of L[], if there are any

    while (i < n1) {

        arr[k] = L[i];

        i++;

        k++;

    }


    // Copy the remaining elements of R[], if there are any

    while (j < n2) {

        arr[k] = R[j];

        j++;

        k++;

    }

}


// Function to implement Merge Sort

void mergeSort(int arr[], int left, int right) {

    if (left < right) {

        // Find the middle point

        int mid = left + (right - left) / 2;


        // Sort first and second halves

        mergeSort(arr, left, mid);

        mergeSort(arr, mid + 1, right);


        // Merge the sorted halves

        merge(arr, left, mid, right);

    }

}


// Function to print the array

void printArray(int arr[], int size) {

    for (int i = 0; i < size; i++)

        printf("%d ", arr[i]);

    printf("\n");

}


int main() {

    int arr[] = {12, 11, 13, 5, 6, 7};

    int arr_size = sizeof(arr) / sizeof(arr[0]);


    printf("Given array: ");

    printArray(arr, arr_size);


    mergeSort(arr, 0, arr_size - 1);


    printf("Sorted array: ");

    printArray(arr, arr_size);


    return 0;

}


Comments

Popular posts from this blog

Write a c program to Create a Circular Linked list and perform Following Operations A. Insertion At Beginning B. Insertion At End C. Insertion After a particular node Insertion Before a particular node E. Insertion at specific position F. Search a particular node G. Return a particular node H. Deletion at the beginning I. Deletion at the end J. Deletion after a particular node K. Deletion before a particular node L. Delete a particular node M. Deletion at a specific position

Write a c program to check whether the created linked list is palindrome or not

Write a c program to Create a Circular single Linked list and perform Following Operations A. Insertion After a particular node B. Insertion Before a particular node C. Search a particular node D. Return a particular node E. Deletion before a particular node F. Delete a particular node