Loading…
DAA · Sorting · Program 05 · In the record
Write a program in c to sort the elements using insertion sort and find its execution time using the time function.
Algorithm: InsertionSort(A, n) 1. Start 2. For i <- 1 to (n-1) do 3. key <- A[i] 4. j <- i-1 5. While (j >= 0 and A[j] > key) do 6. A[j+1] <- A[j] 7. j <- j-1 8. A[j+1] <- key 9. Print the sorted array A 10. Stop
1#include<stdio.h>2#include<time.h>3 4int main() {5 int n,i,j,key,count=0;6 printf("Enter the number of elements:");7 scanf("%d",&n);8 int a[n];9 printf("Enter the elements:");10 for(i=0;i<n;i++)11 scanf("%d",&a[i]);12 13 clock_t start=clock();14 for(i=1;i<n;i++) {15 key=a[i];16 j=i-1;17 while(j>=0) {18 count++;19 if(a[j]>key) {20 a[j+1]=a[j];21 j--;22 }23 else24 break;25 }26 a[j+1]=key;27 }28 clock_t end=clock();29 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;30 31 printf("\nAfter insertion sorting:");32 for(i=0;i<n;i++)33 printf("\t%d",a[i]);34 printf("\nNumber of comparisons:%d",count);35 printf("\nTime taken:%f seconds",time_taken);36 printf("\nTime complexity: best case O(n), worst case O(n^2)");37 printf("\nSpace complexity: O(1)");38 printf("\n");39 return 0;40}6 ⏎ 42 8 27 14 35 19Enter the number of elements:6 Enter the elements:42 8 27 14 35 19 After insertion sorting: 8 14 19 27 35 42 Number of comparisons:12 Time taken:0.000005 seconds Time complexity: best case O(n), worst case O(n^2) Space complexity: O(1)
Run program 05 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.