Loading…
DAA · Sorting · Program 09 · In the record
Write a program in c to sort the elements using merge sort and find its execution time using the time function.
Algorithm: MergeSort(A, low, high) 1. Start 2. If (low < high) then 3. mid <- (low+high)/2 4. MergeSort(A, low, mid) 5. MergeSort(A, mid+1, high) 6. Merge(A, low, mid, high) 7. Stop Algorithm: Merge(A, low, mid, high) 1. n1 <- mid-low+1, n2 <- high-mid 2. Copy A[low..mid] into L[0..n1-1] and A[mid+1..high] into R[0..n2-1] 3. i <- 0, j <- 0, k <- low 4. While (i < n1 and j < n2) do 5. if L[i] <= R[j] then 6. A[k] <- L[i], i <- i+1 7. else 8. A[k] <- R[j], j <- j+1 9. k <- k+1 10. Copy the remaining elements of L and R into A 11. Return
1#include<stdio.h>2#include<time.h>3 4int count=0;5 6void merge(int a[],int low,int mid,int high) {7 int n1=mid-low+1,n2=high-mid;8 int left[n1],right[n2];9 int i,j,k;10 11 for(i=0;i<n1;i++)12 left[i]=a[low+i];13 for(j=0;j<n2;j++)14 right[j]=a[mid+1+j];15 16 i=0;17 j=0;18 k=low;19 while(i<n1 && j<n2) {20 count++;21 if(left[i]<=right[j])22 a[k++]=left[i++];23 else24 a[k++]=right[j++];25 }26 while(i<n1)27 a[k++]=left[i++];28 while(j<n2)29 a[k++]=right[j++];30}31 32void mergeSort(int a[],int low,int high) {33 if(low<high) {34 int mid=(low+high)/2;35 mergeSort(a,low,mid);36 mergeSort(a,mid+1,high);37 merge(a,low,mid,high);38 }39}40 41int main() {42 int n,i;43 printf("Enter the number of elements:");44 scanf("%d",&n);45 int a[n];46 printf("Enter the elements:");47 for(i=0;i<n;i++)48 scanf("%d",&a[i]);49 50 clock_t start=clock();51 mergeSort(a,0,n-1);52 clock_t end=clock();53 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;54 55 printf("\nAfter merge sorting:");56 for(i=0;i<n;i++)57 printf("\t%d",a[i]);58 printf("\nNumber of comparisons:%d",count);59 printf("\nTime taken:%f seconds",time_taken);60 printf("\nTime complexity: O(n log n)");61 printf("\nSpace complexity: O(n)");62 printf("\n");63 return 0;64}6 ⏎ 42 8 27 14 35 19Enter the number of elements:6 Enter the elements:42 8 27 14 35 19 After merge sorting: 8 14 19 27 35 42 Number of comparisons:11 Time taken:0.000008 seconds Time complexity: O(n log n) Space complexity: O(n)
Run program 09 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.