Ask Question

Name:
Title:
Your Question:

Answer Question

Name:
Your Answer:
User Submitted Source Code!


Description:
  selection and insertion sort with time
Language: C/C++
Code:
#include<stdio.h>
#include<sys/time.h>
#include<time.h>
void selection_sort(int*,int);
void insertion_sort(int*,int);

main()
{

    struct timeval t1,t2;



    int i,n;
    scanf("%d",&n);
    int a[n];
    int b[n];
    for(i = 0;i<n;i++)
     {
        scanf("%d",&a[i]);
     }


for(i = 0;i<n;i++)
     {
        b[i]=a[i];

     }




printf("SELECTION SORT");


          gettimeofday(&t1,NULL);
        selection_sort(a,n);
          gettimeofday(&t2,NULL);
          printf("%ld seconds \n",t2.tv_sec-t1.tv_sec);
        printf("%ld microseconds\n",t2.tv_usec-t1.tv_usec);
                printf("sorted elements:\n");
                for(i=0;i<n;i++)
                {
                   printf("%d\n",a[i]);
                }
              


printf("INSERTION SORT");

          gettimeofday(&t1,NULL);
        insertion_sort(b,n);
          gettimeofday(&t2,NULL);
          printf("%ld seconds \n",t2.tv_sec-t1.tv_sec);
        printf("%ld microseconds\n",t2.tv_usec-t1.tv_usec);
                printf("sorted elements:\n");
                for(i=0;i<n;i++)
                {
                   printf("%d\n",b[i]);
                }





}
void selection_sort(int *a,int n)
{
     int i,j,min,t;
     for(i = 0;i<n-1;++i)
     {
          min = i;
          for(j = i+1;j<n;++j)
          {
               if(a[j]<a[min])
                    min = j;
          }
          if(i!=min)
          {
               t = a[i];
               a[i] = a[min];
               a[min] = t;
          }
     }
}






void insertion_sort(int *a,int n)
{
     int i,j,k,key;

     for(i=1;i<n;++i)
     {
          key=a[i];
          j=i-1;
          while(j>=0 && a[j]>key)
          {
               a[j+1]=a[j];
               --j;
          }
          a[j+1]=key;
     }
}













Comments: