Skip to main content

Write a program to measure the performance using time function between bubble sort and quick sort algorithm.

Free Discussion

#include<stdio.h> #include<conio.h> void quick ( int arr[], int begin, int end ); int count=0, count_q=0; void bubble(int barr[],int n) { int i,j,t; for(i=n-2;i>=0;i--) { for(j=0;j<=i;j++) { count++; if(barr[j]>barr[j+1]) { t=barr[j]; barr[j]=barr[j+1]; barr[j+1]=t; count=count+3; } count++; } count++; } } void main() { int barr[100],qarr[100],n,i; clrscr(); printf("\n\n Enter integer value for total no.s of elements to be sorted: "); scanf("%d",&n); for( i=0;i<=n-1;i++) { printf("\n Enter integer value for element no.%d : ",i+1); scanf("%d",&barr[i]); qarr[i]=barr[i]; } printf("\n\nBefor sorted elements are:\n"); for(i=0;i<=n-1;i++) printf("%d, ",barr[i]); bubble(barr,n); printf("\n\n Finally sorted array using BUBBLE sort is: \n"); for( i=0;i<=n-1;i++) printf("%d, ",barr[i]); printf("\nTime required for BUBBLE sort is: %d",count); quick ( qarr, 0, n- 1 ); printf("\n\n Finally sorted array using QUICK sort is: \n"); for( i=0;i<=n-1;i++) printf("%d, ",qarr[i]); printf("\nTime required for QUICK sort is: %d",count_q); getch(); } void quick ( int qarr[], int begin, int end ) { int num,temp; num = end - begin + 1; count_q++; //int temp; count_q++; if ( num > 2 ) { int left,right; left = begin + 1; count_q++; right = end; count_q++; while ( left < right ) { count_q++; while ( left <= end && qarr[left] <= qarr[begin] ) { left++; count_q++; } count_q++; while ( qarr[right] > qarr[begin] ) { right--; count_q++; } count_q++; if ( left < right ) { temp=qarr[left]; count_q++; qarr[left]=qarr[right]; count_q++; qarr[right]=temp; count_q++; } }count_q++; temp=qarr[begin]; count_q++; qarr[begin]=qarr[right]; count_q++; qarr[right]=temp; count_q++; quick ( qarr, begin, right - 1 ); count_q++; quick ( qarr, right + 1, end ); count_q++; } else if ( num == 2 ) { count_q++; if ( qarr[end] < qarr[begin] ) { temp=qarr[end]; count_q++; qarr[end]=qarr[begin]; count_q++; qarr[begin]=temp; count_q++; } } } ------------------------------------------------------ Out put: Enter integer value for total no.s of elements to be sorted:6 Enter integer value for element no.1:23 Enter integer value for element no.2:43 Enter integer value for element no.3:12 Enter integer value for element no.4:74 Enter integer value for element no.5:66 Enter integer value for element no.6:86 Befor sorted elements are: 23, 43, 12, 74, 66,86 Finally sorted array using BUBBLE sort is: 12, 23, 43, 66, 74, 86 Time required for BUBBLE sort is:50 Finally sorted array using QUICK sort is: 12, 23, 43, 66, 74, 86 Time required for BUBBLE sort is:56

Quote: “When one door of happiness closes, another opens; but often we look so long at the closed door that we do not see the one which has been opened for us.” -Helen Keller