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