Loading…
DAA · Sorting · Program 08 · In the record
Write a program in c to sort the elements using quick sort and find its execution time using the time function.
Algorithm: QuickSort(A, low, high) 1. Start 2. If (low < high) then 3. p <- Partition(A, low, high) 4. QuickSort(A, low, p-1) 5. QuickSort(A, p+1, high) 6. Stop Algorithm: Partition(A, low, high) 1. pivot <- A[high] 2. i <- low-1 3. For j <- low to (high-1) do 4. if A[j] <= pivot then 5. i <- i+1 6. swap A[i] and A[j] 7. swap A[i+1] and A[high] 8. Return i+1
1#include<stdio.h>2#include<time.h>3 4int count=0;5 6int partition(int a[],int low,int high) {7 int pivot=a[high];8 int i=low-1,j,temp;9 10 for(j=low;j<high;j++) {11 count++;12 if(a[j]<=pivot) {13 i++;14 temp=a[i];15 a[i]=a[j];16 a[j]=temp;17 }18 }19 temp=a[i+1];20 a[i+1]=a[high];21 a[high]=temp;22 return i+1;23}24 25void quickSort(int a[],int low,int high) {26 if(low<high) {27 int p=partition(a,low,high);28 quickSort(a,low,p-1);29 quickSort(a,p+1,high);30 }31}32 33int main() {34 int n,i;35 printf("Enter the number of elements:");36 scanf("%d",&n);37 int a[n];38 printf("Enter the elements:");39 for(i=0;i<n;i++)40 scanf("%d",&a[i]);41 42 clock_t start=clock();43 quickSort(a,0,n-1);44 clock_t end=clock();45 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;46 47 printf("\nAfter quick sorting:");48 for(i=0;i<n;i++)49 printf("\t%d",a[i]);50 printf("\nNumber of comparisons:%d",count);51 printf("\nTime taken:%f seconds",time_taken);52 printf("\nTime complexity: O(n log n) average, O(n^2) worst");53 printf("\nSpace complexity: O(log n) average, O(n) worst");54 printf("\n");55 return 0;56}6 ⏎ 42 8 27 14 35 19Enter the number of elements:6 Enter the elements:42 8 27 14 35 19 After quick sorting: 8 14 19 27 35 42 Number of comparisons:9 Time taken:0.000006 seconds Time complexity: O(n log n) average, O(n^2) worst Space complexity: O(log n) average, O(n) worst
Run program 08 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.