You are on page 1of 5

DSA - Insertion Sort program calculating the time complexity

#include<stdio.h> #include<time.h> int main() { int A[20], N, Temp, i, j; time_t t1,t2; printf("\n\n\t ENTER THE NUMBER OF TERMS...: "); scanf("%d", &N); printf("\n\t ENTER THE ELEMENTS OF THE ARRAY...:\n"); for(i=0; i<N; i++) { scanf("\n\t\t%d", &A[i]); } (void) time(&t1); for(i=1; i<N; i++) { Temp = A[i]; j = i-1; while(Temp<A[j] && j>=0) { A[j+1] = A[j]; j = j-1; } A[j+1] = Temp; } (void) time(&t2); printf("\n\tTHE ASCENDING ORDER LIST IS...:\n"); for(i=0; i<N; i++) printf("\n\t\t\t%d", A[i]); printf("\nTotal time taken in sorting is...%f",(double)(t2t1)); return 0; }

DSA - Quick Sort program With complexity calculation


#include<stdio.h> #define MAX 10000 void statement(int *); void display(int *); void swap(int *,int *); void quicksort(int *,int ,int ); void best_case_array(int *); void worst_case_array(int *); void average_case_array(int *); int main() { int array[MAX],s; printf("Enter your choice:\nEnter 1 for Best Case.\n" "Enter 2 for Worst Case.\n" "Enter 3 for Average Case....\n"); scanf("%d",&s); switch(s) { case 1: best_case_array(array); statement(array); break; case 2: worst_case_array(array); statement(array); break; case 3: average_case_array(array); statement(array); break; default: printf("Please Enter Valid Number....\n"); break; } return 0; }

void statement(int array[]) { printf("Entered Array is: "); display(array); double t1=clock();/*Some compile shows warning message here like "missing prototype for 'clock'" in pelles c compiler because of this it will show time taken is 0.000000*/ quicksort(array,0,MAX-1); double t2=clock(); printf("\nSorted Array is: "); display(array); printf("\nT1= %f T2= %f ",t1,t2); printf("\nTime taken for sorting is: %f\n",(t2-t1)); } void display(int array[]) { int i; for(i=0;i<MAX;i++) { printf("%d ",array[i]); } } void best_case_array(int array[]) { int i; for(i=0;i<MAX;i++) { array[i]=i+1; } } void worst_case_array(int array[]) { int i; int j=MAX; for(i=0;i<MAX;i++)

{ array[i]=j; j--; } } void average_case_array(int array[]) { int i; for(i=0;i<MAX;i++) { array[i]=rand(1,(MAX-1));/*Here rand(arg1,arg2) is the syntax for rand function or it can take void argument according to compiler*/ } } void swap(int *i,int *j) { int temp; temp=*i; *i=*j; *j=temp; } void quicksort(int array[],int m,int n) { int key,i,j,k; if(m<n) { k=(m+n)/2; swap(&array[m],&array[k]); key=array[m]; i=m+1; j=n; while(i<=j) { while((i<=n)&&(array[i]<=key)) i++; while((j>=m)&&(array[j]>key)) j--; if(i<j)

swap(&array[i],&array[j]); } swap(&array[m],&array[j]); quicksort(array,m,j-1); quicksort(array,j+1,n); } }

You might also like