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