[C Program] Compare The Time Taken By Selection Sort , Insertion Sort & Bubble Sort in C

C Program to Compare The Time taken by
Selection Sort, Bubble Sort & Insertion Sort

#include<stdio.h>
#include<conio.h>
#include<time.h>

void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}

void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}

void selectionSort(int arr[], int n)
{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}

int main()
{
int n,arr[50],i;
printf("Enter The No. of Elements :");
scanf("%d",&n);
printf("Enter The Array Elements :");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
clock_t time,end;
time=clock();
bubbleSort(arr,n);
end=clock();
printf("Sorted Array is:");
for(i=0;i<n;i++)
printf("%d ",arr[i]);
double total =((double)(end-time)/CLOCKS_PER_SEC);
printf("\nBubble Sort Time=");
printf("%lf",total);
clock_t time1,end1;
time1=clock();
insertionSort(arr,n);
end1=clock();
double total1 =((double)(end1-time1)/CLOCKS_PER_SEC);
printf("\nInsertion Sort Time=");
printf("%lf",total1);
clock_t time2,end2;
time2=clock();
selectionSort(arr,n);
end2=clock();
double total2 =((double)(end2-time2)/CLOCKS_PER_SEC);
printf("\nSelection Sort Time=");
printf("%lf",total2);
}


OUTPUT :

The Time Taken By the sorting is different for
different Computers.
The Above Output Screen shots from Mobile.
Run on CPP Droid

Post a Comment

Previous Post Next Post