Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.1 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void merge(int arr[], int l, int m, int r) {
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;
  
    int L[n1], R[n2];
  
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];
  
    i = 0;
    j = 0;
    k = l;
    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];
        i++;
        k++;
    }
  
    while (j < n2) {
        arr[k] = R[j];
        j++;
        k++;
    }
}
  
void mergeSortIterative(int arr[], int n) {
    int curr_size, left_start;
  
    for (curr_size = 1; curr_size <= n-1; curr_size = 2*curr_size) {
        for (left_start = 0; left_start < n-1; left_start += 2*curr_size) {
            int mid = left_start + curr_size - 1;
  
            int right_end = left_start + 2*curr_size - 1;
  
            if (right_end > n-1)
                right_end = n-1;
  
            merge(arr, left_start, mid, right_end);
        }
    }
}

void mergeSortRecursive(int arr[], int l, int r) {
    if (l < r) {
        int m = l+(r-l)/2;
  
        mergeSortRecursive(arr, l, m);
        mergeSortRecursive(arr, m+1, r);
  
        merge(arr, l, m, r);
    }
}

void printArray(int arr[], int size) {
    int i;
    for (i=0; i < size; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

int main() {
    int arr[10000];
    for (int i = 0; i < 10000; i++) {
        arr[i] = i;
    }

    clock_t start, end;
    double cpu_time_used;

    start = clock();
    mergeSortIterative(arr, 10000);
    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("Time taken by iterative merge sort: %f seconds\n", cpu_time_used);

    start = clock();
    mergeSortRecursive(arr, 0, 9999);
    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    printf("Time taken by recursive merge sort: %f seconds\n", cpu_time_used);

    return 0;
}
Leave a Comment