0% found this document useful (0 votes)
2 views4 pages

Lab 1 DAA

Uploaded by

mananjani335
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Lab 1 DAA

Uploaded by

mananjani335
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Lab – 1

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

// Function to merge two subarrays of arr[].

// First subarray is arr[l..m], and the second subarray is arr[m+1..r].

void merge(int arr[], int l, int m, int r) {

int i, j, k;

int n1 = m - l + 1;

int n2 = r - m;

// Create temporary arrays

int L[n1], R[n2];

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

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

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

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

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

// Merge the temporary arrays back into arr[l..r]

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++;

// 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++;

// Main merge sort function

void mergeSort(int arr[], int l, int r) {

if (l < r) {

// Same as (l+r)/2, but avoids overflow for large l and r

int m = l + (r - l) / 2;

// Sort first and second halves

mergeSort(arr, l, m);

mergeSort(arr, m + 1, r);
// Merge the sorted halves

merge(arr, l, m, r);

int main() {

srand(time(NULL));

int n;

printf("Enter the number of elements: ");

scanf("%d", &n);

int arr[n];

// Initialize the array with random values

for (int i = 0; i < n; i++) {

arr[i] = rand() % 1000; // Random numbers between 0 and 999

printf("Original Array:\n");

for (int i = 0; i < n; i++) {

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

printf("\n");

clock_t start_time = clock(); // Record the start time

mergeSort(arr, 0, n - 1);

clock_t end_time = clock(); // Record the end time


printf("Sorted Array:\n");

for (int i = 0; i < n; i++) {

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

printf("\n");

double execution_time = (double)(end_time - start_time) / CLOCKS_PER_SEC;

printf("Merge Sort Execution Time: %.6f seconds\n", execution_time);

return 0;

You might also like